This may be a javascript 101 or Backbone 100 questions. But I feel comfortable in asking this beginning question and not being made fun of here 🙂
The following code snippet is from Code School’s Anatomy of Backbone JS course:
render: function(){
this.collection.forEach(this.addOne, this);
}
addOne: function(todoItem){
var todoView = new TodoView({model: todoItem});
this.$el.append(todoView.render().el);
}
The addOne function is being called from the render function. addOne function definition shows that one parameter “todoItem” is being passed to it. But if you look at the call to addOne from render, it does not show an argument/parameter being passed to it. How is it possible that the code works correctly?
Thanks in advance for your time.
Bharat
The first argument of the
forEachfunction is a callback function, and theforEachfunction calls that function, handing in each element of the array as a parameter.More visually, your call to
forEachwould lead to:.. where
nrepresents the last index of the arraythis.collection.The function
addOnewill ignore the second and third parameters becauseaddOneonly specified one parameter. Also,thisfromaddOnewill be set to thethisvariable fromrender.More details are available from the Mozilla Developer Network and MSDN.