Skip to content

Instantly share code, notes, and snippets.

@lsmith
Forked from hatched/event-handler.js
Created February 24, 2011 22:44
Show Gist options
  • Save lsmith/843061 to your computer and use it in GitHub Desktop.
Save lsmith/843061 to your computer and use it in GitHub Desktop.
/**
* Adds a method to the Y.Base prototype to handle events so that when a widget
* or plugin becomes destroyed all events attached are detached.
*
* Requires Y.Lang & Y.Array
*/
YUI.add('event-handler', function(Y) {
Y.Plugin.EventManager = Y.Base.create('eventManager', Y.Base, [], {
initializer: function () {
this._subs = [];
this.get('host').on('destroy', this.clean);
},
register: function (sub) {
if (Y.Lang.isArray(sub)) {
Y.Array.each(sub, this.register, this);
} else if (sub.detach) {
this._subs.push(sub);
}
return this;
},
clean: function () {
new Y.EventHandle(this._subs).detach();
}
}, {
NS: 'events'
});
Y.Base.ATTRS.monitorEvents = {
setter: function (val) {
var method = (val) ? 'plug' : 'unplug';
this[method](Y.Plugin.EventManager);
}
};
}, '0.1', { requires: ['plugin'] });
-= To Use Within Widget Or Plugin=-
var thing = new Y.BaseDerivedClass({
monitorEvents: true,
...
});
-=To Add=-
this.events.register([
Y.one('window').on('resize', function, this),
Y.one('#loginform').on('submit', function, this)
]);
-=OR=-
this.events.register(
Y.one('#loginform').on('submit', this._formSubmit, this)
);
-=To Destroy=-
this.destroy();
-=OR=-
this.events.clean();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment