Skip to content

Instantly share code, notes, and snippets.

@StevenLangbroek
Last active August 29, 2015 14:19
Show Gist options
  • Save StevenLangbroek/72b6996ce056bb39c0d2 to your computer and use it in GitHub Desktop.
Save StevenLangbroek/72b6996ce056bb39c0d2 to your computer and use it in GitHub Desktop.
Backbone Utility for listening to multiple events on another Class (has to extend Backbone.Events)
import _ from 'underscore';
/**
* Backbone utility, to listen to multiple Backbone Events,
* structured like the native 'events' hash. Shortcuts things like
* `collectionEvents` on CollectionView, and `triggers` on Views.
* @param {class instance} obj object to listen to.
* @param {object} eventHash hash of events (prop:event, prop on current object) and handlers (value)
* @param {class instance} context optional context to call handlers with.
* @return {null} Doesn't return.
*
* Example:
*
* const SomeView = BaseView.extend({
* listenToMany,
* initialize(options){
* this.collection = options.collection;
* this.parentView = options.parentView;
* this.controller = options.controller;
* },
* sharedEvents: {
* 'controller:newData': 'render',
* 'parentView:someEvent': 'onParentViewSomeEvent',
* 'collection:add': 'onCollectionAdd',
* 'collection:remove': 'onCollectionRemove'
* },
* initialize(options){
* this.listenToMany(this.sharedEvents);
* },
* onParentViewSomeEvent(e){
* e.preventDefault();
* console.log('something happened in parentView');
* },
* onCollectionAdd(model){
* this.renderNewChild(model);
* },
* onCollectionRemove(model){
* this.removeChildViewByModel(model);
* }
* });
*/
export default function(eventHash, context = this){
_.each(eventHash, (method, propAndEvent) => {
let [prop, event] = propAndEvent.split(':');
this.listenTo(this[prop], event, _.bind(this[method], context));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment