Last active
August 29, 2015 14:19
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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