Understanding Bind and bindAll in Backbone.js
http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html
by FiNGAHOLiC
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
JavaScript
// 'this' is window
(function(){
var func = function beautiful(){
console.log(this + ' is beautful');
};
func(); // => [object DOMWindow] is beautiful
}());
// 'this' is 'Internet'
(function(){
var func = function beautiful(){
console.log(this + ' is beautful');
};
func.apply('Internet'); // => Internet is beautiful
}());
// 'this' is 'Beach'
(function(){
var func = function beautiful(){
console.log(this + ' is beautful');
};
func.apply('Beach'); // => Beach is beautiful
}());
// 'this' is john, instance of Developer
(function(){
var Developer = function(skill){
this.skill = skill;
this.says = function(){
console.log(this.skill + ' rocks!');
};
};
var john = new Developer('Ruby');
john.says(); // => Ruby rocks!
}());
// func is being invoked in the global context.
// And window doesn't have any attribute called skill.
(function(){
var Developer = function(skill){
this.skill = skill;
this.says = function(){
console.log(this.skill + ' rocks!');
};
};
var john = new Developer('Ruby');
var func = john.says;
func(); // => undefined rocks!
}());
// Solution for this problem above
(function(){
var Developer = function(skill){
this.skill = skill;
this.says = function(){
console.log(this.skill + ' rocks!');
};
};
var john = new Developer('Ruby');
var func = john.says;
func.apply(john); // => Ruby rocks!
}());
// Solution for this problem above by using bind function of underscore.js
(function(){
var Developer = function(skill){
this.skill = skill;
this.says = function(){
console.log(this.skill + ' rocks!');
};
};
var john = new Developer('Ruby');
var func = _.bind(john.says, john);
func.apply(john); // => Ruby rocks!
}());
// Not correct
(function(){
var View = Backbone.View.extend({
...