Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between bind and on in backbone

What is the difference between bind() and on() methods in Backbone.js

Documentation for on() : On method documentation at backbone.js

Documentation for bind() : Bind method documentation at underscore.js

Which of the two should be used to bind custom events for objects ?

Usage example:

this.bind('myEvent', this.render, this);
this.on('myEvent', this.render, this);
like image 929
Sachin Avatar asked Apr 07 '13 17:04

Sachin


2 Answers

this.bind('myEvent', this.render, this);
this.on('myEvent', this.render, this);

These are exactly equivalent and are not related to the underscore bind function.

Here is some code from Backbone source:

// Aliases for backwards compatibility.
Events.bind   = Events.on;
Events.unbind = Events.off;

So, in both lines of your code, you are calling the same function.

like image 117
Paul Hoenecke Avatar answered Oct 03 '22 23:10

Paul Hoenecke


_.bind in underscore has nothing to do with bind in Backbone event object. ( or underscore )

_.bind in underscore is used when you want to bind a function to a context ( wrap it in a closure ). So when the function is called the context (this ) doesnt change .

the Backbone documentation explicitly says the bind method in the event is an alias to the on method. So why do you link to the bind definition in underscore ?

http://backbonejs.org/#Events-on

like image 36
mpm Avatar answered Oct 04 '22 00:10

mpm