Created
June 14, 2011 13:13
-
-
Save assertchris/1024865 to your computer and use it in GitHub Desktop.
Mootools Event Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://jsfiddle.net/sixtyseconds/HrKHp/ | |
var Proxy = new Class({ | |
'addDelegate': function(object, events) { | |
var self = this; | |
if (!self.delegates) { | |
self.delegates = []; | |
} | |
Array.each(Array.from(events), function(event) { | |
var callback = function() { | |
object.fireEvent(event); | |
}.bind(self); | |
self.delegates.push({ | |
'object': object, | |
'event': event, | |
'callback': callback | |
}); | |
self.addEvent(event, callback); | |
}); | |
}, | |
'removeDelegate': function(object, event) { | |
var self = this; | |
Array.each(self.delegates, function(delegate, i) { | |
if (delegate.object == object) { | |
if (!event || delegate.event == event) { | |
self.removeEvent(delegate.event, delegate.callback); | |
delete self.delegates[i]; | |
} | |
} | |
}); | |
} | |
}); | |
var Foo = new Class({ | |
Implements: [Options, Events, Proxy], | |
'options': { | |
'onEvent1': function() { | |
console.log('[Foo] onEvent1'); | |
} | |
}, | |
'initialize': function(options) { | |
this.setOptions(options); | |
var bar = new Bar(); | |
this.addDelegate(bar, 'onEvent2'); | |
this.addDelegate(bar, ['onEvent3', 'onEvent4']); | |
this.removeDelegate(bar, 'onEvent3'); | |
} | |
}); | |
var Bar = new Class({ | |
Implements: [Options, Events], | |
'options': { | |
'onEvent2': function() { | |
console.log('[Bar] onEvent2'); | |
}, | |
'onEvent3': function() { | |
console.log('[Bar] onEvent3'); | |
}, | |
'onEvent4': function() { | |
console.log('[Bar] onEvent4'); | |
} | |
}, | |
'initialize': function(options) { | |
this.setOptions(options); | |
} | |
}); | |
var something = new Foo(); | |
something.fireEvent('onEvent1'); | |
something.fireEvent('onEvent2'); | |
something.fireEvent('onEvent3'); | |
something.fireEvent('onEvent4'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment