0

I am studying Backbone.js through the example todomvc application from here: http://todomvc.com/architecture-examples/backbone/

And I'm sort of stuck in the app-view.js part here: https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/backbone/js/views/app-view.js

Here's the snippet of the code:

    // Add a single todo item to the list by creating a view for it, and
    // appending its element to the `<ul>`.
    addOne: function (todo) {
        var view = new app.TodoView({ model: todo });
        this.$list.append(view.render().el);
    },

Where did the 'todo' variable comes from on the function 'addOne'? I searched the whole project files and so far didn't find any specific function that specifies or initialize the 'todo' variable. I tried to read the Backbone.js and Underscore.js docs on their website and so far haven't find the explanation.

PrestaShopDeveloper
  • 3,110
  • 3
  • 21
  • 30
Anzhari
  • 47
  • 1
  • 8
  • from `initialize: function() {... this.listenTo(app.todos, 'add', this.addOne); ...}` app-view.js line 27 , also `'keypress #new-todo': 'createOnEnter'` triggers `createOnEnter` which creates model in collection `app.todos.create(this.newAttributes())` – Evgeniy Aug 26 '14 at 06:28

1 Answers1

1

Ok to make what @Evgeniy said more readable..

When you listen to 'add' on a collection the first thing that is passed to the listening method is the added model:

this.listenTo(app.todos, 'add', this.addOne);

Here is the line in the backbone source:

(model = toAdd[i]).trigger('add', model, this, options);

So you can see the first param is the added model, then the collection, then any options passed through from this.collection.add(model, [options]).

addAll is also calling addOne - it loops over all the models and adds views for them one-by-one:

app.todos.each(this.addOne, this);

In each case the first param is going to be a model which needs a view added for it.

Dominic
  • 62,658
  • 20
  • 139
  • 163
  • @Evgeniy So, you're saying that this function: 'this.listenTo(app.todos, 'add', this.addOne);' Automatically pass argument into 'addOne' function, and the argument is the model name of the collection. Is that correct? – Anzhari Aug 26 '14 at 12:20
  • @AnzhariPurnomo Yes - it automatically passes the model that was just added to the collection – Dominic Aug 26 '14 at 12:58
  • Can you help explain to me step by step on the source code? And preferrably the basic concept on how is this possible, so the next time I stumbled into something similar maybe I could try to understand by myself. :D – Anzhari Aug 26 '14 at 14:03