Skip to content

Instantly share code, notes, and snippets.

@DaveStein
Created November 22, 2011 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save DaveStein/1384615 to your computer and use it in GitHub Desktop.
Save DaveStein/1384615 to your computer and use it in GitHub Desktop.
Singleton wrapper around $.Callbacks to emulate Backbone events
var Events = {
// Store each registered $.Callbacks object by namespace
cache : {},
// Bind callback to event along with a context
bind : function( ev, callback, context, options ) {
// Make $.Callbacks default to having stopOnFalse
options = options || 'stopOnFalse';
// If this callback list does not exist, create it
if ( !this.cache[ ev ] ) {
this.cache[ ev ] = $.Callbacks( options );
}
// Add callback to cache, make sure callback gets proper context
this.cache[ ev ].add( $.proxy( callback, context ) );
}, // bind
unbind : function( ev, callback ) {
// Ignore unbind if it didn't exist
if ( !this.cache[ ev ] ) {
return;
}
this.cache.remove( callback );
}, // unbind
trigger : function( ev ) {
// Ignore trigger if it doesn't exist
if ( !this.cache[ ev ] ) {
return;
}
// Get dynamic number of arguments, knowing first argument is always event
var args = [].slice.call( arguments ),
pass = args.splice(1);
// Call $.Callbacks fire method with right arguments
this.cache[ ev ].fire.apply( null, pass );
} // trigger
}; // Events
@jaubourg
Copy link

Line #30: you missed the [ev]
Line #46: you could use fireWith( null, pass );

@DaveStein
Copy link
Author

Thanks @jaubourg for that catch on #30. I didn't need unbind where I first wrote this so didn't see that bug yet. Also you're right about fireWith since fire just calls fireWith anyway. Didn't look at the internals until just now.

@jaubourg
Copy link

Here is my take on it. I have removed the options in bind given how situational it is (will work the first time, not the second, etc).

https://gist.github.com/1387553

@DaveStein
Copy link
Author

DaveStein commented Nov 23, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment