Out of date? bindAll?

Of course, I am reading the manual, but as I see in the classic example, it doesnโ€™t really matter if I comment out the line with the binding. Are the default methods bound?

(function($){
    var ListView = Backbone.View.extend({
        el: $('#TheList'), // el attaches to existing element
        events: {
            'click button#add': 'addItem'
        },

        initialize: function(){
            // _.bindAll(thathis, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here

            this.counter = 0; // total number of items added thus far
            this.render();
        },

        render: function(){
            $(this.el).append('<button id="add">Add list item</button>');
            $(this.el).append('<ul></ul>');
            // console.log(this);
            // console.log(this.el);
        },

        addItem: function(){
            this.counter++;
            $('ul', this.el).append('<li>hello world'+this.counter+'</li>');
        }
    });

    var listView = new ListView();

})(jQuery);
+3
source share
2 answers

Jax is right that you don't need to manually bind View methods and events in the latest version of Backbone (currently 1.1.0). There are earlier versions where this is also true, but I do not remember which ones.

There are times when you need to bind view methods so that they work correctly. These cases are the main areas of Javascript and are not specifically related to Backbone JS.

_.bindAll. , _.bind, Underscore JS.

, Backbone, _.bind. Backbone Events. , Collection Model, Events, .

, , .

this.collection.on('add', this.appendItem, this);

this.model.on('change', this.render, this);

render. render , .

:

this.collection.bind('add', this.appendItem, this);

on bind, , on. bind . , Backbone on off bind unbind.

jsFiddles, , . : http://arturadib.com/hello-backbonejs/docs/5.html

, . , , , , Backbone 1.10. , _.bindAll.

1 : http://jsfiddle.net/ChTjs/

:

initialize: function() {
    this.collection = new List();
    this.collection.on('add', this.appendItem, this);
    this.collection.on('add', this.updateCount, this);
    this.collection.on('remove', this.updateCount, this);
    this.counter = 0;
    this.render();
},

:

this.model.on('change', this.render, this);
this.model.on('remove', this.unrender, this);

jsFiddle, . http://jsfiddle.net/LpEW8/1/

, . , Backbone. Binding "this"

2

, listenTo. , /, listenTo. this on. , , on

, :

this.collection.on('add', this.appendItem, this);
this.collection.on('add', this.updateCount, this);
this.collection.on('remove', this.updateCount, this);

:

this.listenTo(this.collection, 'add', this.appendItem);
this.listenTo(this.collection, 'add', this.updateCount);
this.listenTo(this.collection, 'remove', this.updateCount);

listenTo Backbone docs: http://backbonejs.org/#Events-listenTo

: http://jsfiddle.net/ChTjs/2/

+3

, ' ' View for all, Backbone View, .

+3

All Articles