Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;(function(emitter){
- "use strict";
- var bind = function( emitter, event, callback, context, once ) {
- var _callback = function() {
- if ( once ) {
- emitter.off(event, callback);
- }
- /*
- * executes the callback in an specific context using parameters sent through emit method
- */
- return callback.apply(context, arguments);
- };
- /*
- * store the callback like a child of the _callback to facilitate remove an specific callback in an event
- */
- _callback.callback = callback;
- return _callback;
- };
- function Emitter() {
- this.listeners = [];
- }
- /*
- * Store an event to run on future
- *
- * Usage:
- * var emitter = Emitter.create();
- *
- * emitter.on('click', function(){
- * console.log('clicked');
- * });
- */
- Emitter.prototype.on = function( event, callback, context, once ) {
- if (!this.listeners[event]) {
- this.listeners[event] = [];
- }
- this.listeners[event].push(bind(this, event, callback, context, once));
- return this;
- };
- /*
- * Store an event to run once on future
- *
- * Usage:
- * var emitter = Emitter.create();
- *
- * emitter.once('click', function(){
- * console.log('clicked');
- * });
- */
- Emitter.prototype.once = function( event, callback, context ) {
- return this.on(event, callback, context, true);
- }
- /*
- * Remove all callbacks associated with a event or removes an specific callback in event
- *
- * Usage:
- * var emitter = Emitter.create();
- *
- * emitter.off('click');
- * emitter.off('click', function(){});
- */
- Emitter.prototype.off = function( event, callback ) {
- var listeners = this.listeners[event],
- count = listeners.length,
- i = 0;
- if (!callback) {
- this.listeners = this.listeners.filter(function( evt ) {
- return event !== evt && (!callback && callback !== evt.callback);
- });
- } else {
- this.listeners[event] = listeners.filter(function(lst) {
- return lst.callback !== callback;
- });
- }
- };
- /*
- * Trigger all callbacks associated with an event
- *
- * Usage:
- * emitter.emit('click');
- * emitter.emit('click', argument1, argument2);
- */
- Emitter.prototype.emit = function() {
- var callback,
- args = Array.prototype.slice.call(arguments),
- event = args.shift(),
- listeners = (this.listeners[event] || []).slice(0);
- while( listeners.length ) {
- callback = listeners.shift();
- callback(args);
- }
- };
- /*
- * Creates an emitter instance. How Emitter was created using prototype,
- * so all instances will have exactly the same methods
- */
- emitter.create = function() {
- return new Emitter();
- };
- })(this.Emitter = {});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement