Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created January 14, 2009 16:32
Show Gist options
  • Save joshuaclayton/46952 to your computer and use it in GitHub Desktop.
Save joshuaclayton/46952 to your computer and use it in GitHub Desktop.
(function($) {
var binder = function(e, dataKey, dataValue) {
var $this = $(this),
oldValue = $this.data(dataKey),
newValue = dataValue,
passed = {
attr: dataKey,
from: oldValue,
to: newValue
};
var isAttribute = !!($this.data(dataKey + "-attribute"));
if(oldValue !== newValue) {
var attrPrefix = isAttribute ? "attr-" : "";
$this.trigger(attrPrefix + dataKey + "-changed", passed);
$this.trigger(attrPrefix + "data-changed", passed);
}
};
var hook = function(original, wrapper) {
return function() {
wrapper.apply(this, arguments);
return original.apply(this, arguments);
};
};
$.observerDefaults = [
{ targetFunction: "attr",
observed: function(attr, val) {
if(val) {
$(this).data(attr + "-attribute", true);
$(this).data(attr, val);
}
}
},
{ targetFunction: "removeAttr",
observed: function(attr) {
$(this).removeData(attr + "-attribute");
$(this).removeData(attr);
}
},
{ targetFunction: "html",
observed: function(val) {
if(val || val === "") {
$(this).data("html", val);
}
}
}
];
$.fn.observeData = function(observers) {
$.each($.observerDefaults.concat(observers), function(idx, observer) {
if(observer && observer.targetFunction && observer.observed) {
$.fn[observer.targetFunction] = hook($.fn[observer.targetFunction], observer.observed);
}
});
if(!$(this).data("currentlyObserved")) {
$(this).data("currentlyObserved", true);
$(this).bind("setData", binder);
}
};
$.observe = function(methods) {
$.each(methods, function(idx, method) {
$.fn[method] = hook($.fn[method], function() {
$(this).observeData();
})
});
}
})(jQuery);
$.observe(["attr", "html"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment