Skip to content

Instantly share code, notes, and snippets.

@SchizoDuckie
Created April 5, 2011 01:21
Show Gist options
  • Save SchizoDuckie/902837 to your computer and use it in GitHub Desktop.
Save SchizoDuckie/902837 to your computer and use it in GitHub Desktop.
A little patch to allow rudimentary wildcard events.
/*
---
name: Channels
description: Mediate Class events. An expanded pattern for pub/sub.
license: MIT-style license.
copyright: Copyright (c) 2010 [Ryan Florence](http://ryanflorence.com/).
authors: Ryan Florence
inspiration:
- dojo.publish [docs](http://docs.dojocampus.org/dojo/publish)
requires:
- Core/Class.Extras
provides: [Channels]
...
*/
(function(){
var mediator = new Events,
methods = {
publishes: function(eventName, channel){
if (typeOf(channel) === 'array'){
channel.each(function(channel){ this.publishes(eventName, channel); }, this);
return;
}
Channels.publishing.push({publisher: this, channel: channel, event: eventName});
this.addEvent(eventName, function(){
for(var chan in mediator.$events) { // Patch SchizoDuckie: search for wildcard events.
if(chan.indexOf('*') > -1 && channel.indexOf(chan.replace('*','')) > -1) {
mediator.fireEvent.call(mediator, chan, arguments[0].channel = channel);
}
}
mediator.fireEvent.call(mediator, channel, arguments);
});
return this;
}.overloadSetter(), // not public MooTools
subscribe: function(channel, fn){
Channels.subscriptions.push({subscriber: this, channel: channel});
mediator.addEvent(channel, fn.bind(this));
return this;
}.overloadSetter()
},
Channels = this.Channels = new Class(methods);
Object.append(Channels, {
publishing: [],
subscriptions: [],
remove: function(channel){
mediator.removeEvents(channel);
Channels.publishing = Channels.publishing.filter(function(item){
return item.channel != channel;
});
},
installTo: function(obj){
if (typeOf(obj) === 'array'){
obj.each(function(item){ Channels.installTo(item); }, this);
return;
}
obj.implement(methods);
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment