Skip to content

Instantly share code, notes, and snippets.

@wiky
Last active October 8, 2016 09:55
Show Gist options
  • Save wiky/6dce063193baaede069751adefd07137 to your computer and use it in GitHub Desktop.
Save wiky/6dce063193baaede069751adefd07137 to your computer and use it in GitHub Desktop.
/**
* Custom Event
*
* @example
* <pre>
* function Foo() {}
* Foo.prototype.render = function() {
* this.trigger('rendered');
* };
* Events.mixin(Foo);
* var foo = new Foo();
* foo.on('rendered', function(){
* alert('rendered triggerd!');
* });
* foo.render();
* </pre>
* @module Events
* @author wiky
* @verson 0.0.2
*/
function Events() {}
Events.prototype = {
/**
* create and bind an event to this Object.
*
* @param {String} type Event type
* @param {Function} handler Event handler
* @param {Object} [params]
* @param {Object} [scope]
* @return {Boolean} Is bind success
*/
on: function(type, handler, scope) {
var ret = false;
this._events = this._events || {};
this._events[type] = this._events[type] || [];
if (typeof type === 'string' && typeof handler === 'function') {
this._events[type].push({
fn: handler,
scope: scope || this
});
ret = true;
}
return ret;
},
/**
* off an event from this Object.
*
* @param {String} type Event type
* @param {Function} [handler] [description]
* @return {Boolean} Is off success
*/
off: function(type, handler) {
var arr, ret = false;
this._events = this._events || {};
arr = this._events[type];
if (arr instanceof Array) {
if (typeof handler === 'function') {
this._events[type] = arr.filter(function(o) {
return o && o.fn !== handler;
});
} else {
delete this._events[type];
}
ret = true;
}
return ret;
},
/**
* trigger the custom event.
*
* @param {String} type Event type
* @param {Object} [args] Event arguments
* @return {Boolean} Break out or not
*/
trigger: function() {
var arr, args, type;
args = ([]).slice.call(arguments);
type = args.shift();
this._events = this._events || {};
arr = this._events[type];
if (arr instanceof Array) {
arr.forEach(function(o) {
if(o && o.fn) {
o.fn.apply(o.scope || this, args);
}
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment