Backbone.js binding and unbinding (no free lunch)

For devs used to other thick client RIAs like actionscript, adding and removing listeners is second nature. But for js devs using an MVC library such as Backbone it may come as an unexpected surprise and be the cause of bugs.
Event driven programming is a good way to go, add listeners, fire the event, handle the event. BUT you have to remember to remove the listeners if the listener is no longer interested or is otherwise being removed from play. If you don't it can be the source of errors and/or leaks.

This is supported in Backbone.js with unbind(), you call it just like you do with bind
i.e.


// add listner to do save if user oks save on save dialog, as well as cancel
saveDialog.unbind("updateOkd", this.updateOkd );
saveDialog.unbind("updateCancelled", this.updateCancelled );



...and here's the bind

// add listner to do save if user oks save on save dialog, as well as cancel
saveDialog.bind("updateOkd", this.updateOkd );
saveDialog.bind("updateCancelled", this.updateCancelled );


That ok for something like a Save dialog triggered by a view (as in this case) since all this is self contained and somewhat sef evident.

But there's another use case in Backbone, the case where a view binds to a shared model and the view is dismissed/replaced by another view. If the first view is not unbound then it's still out there listening to the model. If you recreate that view, now there's a 2nd instance of the view listening.
I know, I discovered this use case today when I noticed actions being called multiple times :-(  (p.s. a likely symptom if this is happening to your ui)

I read there is a remove() method you can call on a view which will also unbind from DOM events but not model events. So you have to unbind from model events yourself.

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more