Skip to content

Instantly share code, notes, and snippets.

@xrado
Last active December 22, 2015 00:28
Show Gist options
  • Save xrado/6389156 to your computer and use it in GitHub Desktop.
Save xrado/6389156 to your computer and use it in GitHub Desktop.
mootools namespaced events
[Element, Window, Document].invoke('implement', {
// Call as element.addNsEvent('event.namespace', function() {});
addNsEvent: function(name, fn) {
// Get event type and namespace
var split = name.split('.'),
eventName = split[0],
namespace = split[1];
// Store the event by its full name including namespace
this.bindCache = this.bindCache || {};
if(this.bindCache[name]) {
this.bindCache[name].push(fn);
} else {
this.bindCache[name] = [fn];
}
// Bind the function to the event
this.addEvent(eventName, fn);
return this;
},
// Call as element.removeNsEvent('event.namespace');
removeNsEvent: function(name) {
// Unbind the specified event
var eventName = name.split('.')[0],
fns = this.bindCache[name],
x = 0,
fn;
for(; fn = fns[x++]; ) {
this.removeEvent(eventName, fn);
}
return this;
},
// Call as element.removeNsEvents('namespace');
removeNsEvents: function(namespace){
var fns,
x,
fn,
self = this;
Object.each(this.bindCache, function(fns,name){
if(name.contains('.') && name.split('.').getLast() == namespace) {
x = 0;
for(; fn = fns[x++]; ) {
self.removeEvent(name.split('.')[0], fn);
}
}
});
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment