I am building a gallery-like picker view in Backbone.js. The picker has many thumbnail views bound to models within a collection and a large preview view for the currently selected thumbnail. Clicking a thumbnail will fire a Backbone.Event to change the preview view’s model. The preview view, however, observes several Backbone events on the model to change state depending on the model’s attributes.
I’m having trouble when it comes to unregistering Backbone events on the previous model and re-registering the same events on the new model. I don’t always have reference to the original .on() registration, and I am tempted to simply call this.model.off() to unregister all the model’s events (I don’t want to destroy any other events the model may have, however). The Backbone.js documentation outlines that calling .off(null, null, context) will unregister the events from the object within the current context. I am uncertain, however, if this will unregister all events just for the current view instance.
Let’s use this setup to register and unregister events:
As is, creating a new MainView won’t destroy the previous bindings and will result in a zombie view. The last 3 lines give the following result:
The accompanying Fiddle : http://jsfiddle.net/9xufW/
Let’s test the
offmethod with a specific context:Calling
yields the expected result
http://jsfiddle.net/9xufW/1/
The callbacks set in the thumbviews are preserved while the callbacks set in the main view are removed. Note that the teardown method could and probably should be used to undelegate DOM events.
Another Fiddle where the model in the main view is replaced instead of destroying/recreating the view http://jsfiddle.net/9xufW/2/