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 forEach function is a callback function, and the forEach function calls that function, handing in each element of the array as a parameter.

More visually, your call to forEach would lead to:

this.collection.forEach(this.addOne, this) -> 
           |this.addOne(this.collection[0], 0, this.collection)
           |this.addOne(this.collection[1], 1, this.collection)
           |this.addOne(this.collection[2], 2, this.collection)
           |this.addOne(this.collection[3], 3, this.collection)
           |this.addOne(this.collection[4], 4, this.collection)
           |...
           |this.addOne(this.collection[n], n, this.collection)

.. where n represents the last index of the array this.collection.

The function addOne will ignore the second and third parameters because addOne only specified one parameter. Also, this from addOne will be set to the this variable from render.

More details are available from the Mozilla Developer Network and MSDN.

其他提示

this.render doesn't directly call this.addOne; rather, it calls this.collection.forEach, passing in this.addOne — the function itself — as an argument. It is this.collection.forEach that invokes the function that you pass it.

For a simpler example, this code-snippet:

function call_function(f, arg)
{
    f(arg);      // call the function you passed in
}

call_function(alert, s);

will do this:

alert(s);

The forEach is implemented in JavaScript 1.6 and if you look at the documentation it is something like this:

array.forEach(callback[, thisArg])

The second parameter in the forEach part of the render is actually the passed argument to the addOne function which is 'todoItem'. The 'this' refers to the array collection, and the addOne callback will be executed for each item in this collection.

Have a look at the documentation. It's all pretty simple actually. forEach calls addOne once for each element in the collection and passes it the parameters (element, index, array). In this case, addOne simply ignores all but the first argument.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top