Skip to content

Instantly share code, notes, and snippets.

@yomotsu
Forked from Takazudo/events.js
Last active December 11, 2015 18:38
Show Gist options
  • Save yomotsu/4642837 to your computer and use it in GitHub Desktop.
Save yomotsu/4642837 to your computer and use it in GitHub Desktop.
/* eventmodule */
/* EventsClass for extend */
var EventModule = function () {}
EventModule.prototype.on = function ( evName, callback ) {
var _this = this;
if ( !this._observer ) {
this._observer = $( {} );
}
this._observer.on( evName, function () {
var args = arguments;
callback.apply( _this._observer, args );
} );
return this;
};
EventModule.prototype.one = function ( evName, callback ) {
var _this = this;
if ( !this._observer ) {
this._observer = $( {} );
}
this._observer.one( evName, function () {
var args = arguments;
callback.apply( _this._observer, args );
} );
return this;
};
EventModule.prototype.off = function () {
if ( !!this._observer ) {
return this;
}
this._observer.off.apply( this._observer, arguments );
return this;
};
EventModule.prototype.trigger = function () {
if ( !this._observer ) {
return this;
}
this._observer.trigger.apply( this._observer, arguments );
return this;
};
/* impl */
var ConcreteCls = function () {
// constructor I am.
};
ConcreteCls.prototype = new EventModule();
/* do it */
var instance = new ConcreteCls;
instance.on( 'foo', function ( e, params ) { alert( params ); } );
instance.trigger( 'foo', { val: 'yes!' } ); // yes!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment