Skip to content

Instantly share code, notes, and snippets.

@roykolak
Created January 30, 2009 18:13
Show Gist options
  • Save roykolak/55173 to your computer and use it in GitHub Desktop.
Save roykolak/55173 to your computer and use it in GitHub Desktop.
Safe observer attaching
function AttachOnce() {
this.behavior($('.' + this.target_class));
this.clean();
}
AttachOnce.prototype.clean = function() {
$('.' + this.target_class).removeClass(this.target_class);
}
AttachOnce.prototype.behavior = function() {
// Will be overwritten.
}
AttachOnce.add = function(class_name, target_class, behavior) {
if(typeof Attach == "undefined") {
Attach = {};
}
Attach[class_name] = function() {
this.target_class = target_class;
AttachOnce.call(this);
}
Attach[class_name].prototype = AttachOnce.prototype;
Attach[class_name].prototype = new Attach[class_name]();
Attach[class_name].prototype.behavior = behavior;
}
// Example Attacher
AttachOnce.add('MyObserver', 'js_observer', function(jquery_selector) {
// Observer code here. Use jquery_selector variable to target elements
});
// Usage
new Attach.MyObserver();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment