简体   繁体   English

在backbone.js中绑定和_.bindAll

[英]Binding and _.bindAll in backbone.js

I am confused about binding and the purpose of _bind.All in backbone.js. 我对_bind.All中绑定和_bind.All的目的感到困惑。 Below is a working code that creates a Modal view #modal and renders out comments fetched from the backend. 下面是一个工作代码,它创建一个模态视图#modal并呈现从后端获取的注释。

Firstly, in the code below, I have in the initialize function _.bindAll(this, 'render', 'renderComments'); 首先,在下面的代码中,我有initialize函数_.bindAll(this, 'render', 'renderComments'); . Whether or not I do _.bindAll() , I have no problems calling this.render() and this.renderComments() inside initialize() . 无论我是否_.bindAll() ,我都可以在initialize()调用this.render()this.renderComments() initialize() Are there any examples of when _.bindAll() will help us and when it will not? 是否有任何关于_.bindAll()何时会帮助我们以及何时不会帮助我们的例子?

ModalView = Backbone.View.extend({
    el: $('#modal'),

    template: _.template( $('#tpl_modal').html() ),

    initialize: function() {
        _.bindAll(this, 'render', 'renderComments');
        this.render();
        this.renderComments();
    },

    render: function() {
        $(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
    },

    renderComments: function() {
        this.commentList = new CommentCollection();
        var self = this;
        this.commentList.fetch({
            data: { post_id: this.model.id},
            processData: true,
            success: function() {
                self.commentListView = new CommentListView({ collection: self.commentList });
            }
        });
    }
});

And

CommentListView = Backbone.View.extend({
    el: '.modal_comments',

    initialize: function() {
        this.render();
    },

    render: function() {
        var self = this;
        this.collection.each( function(comment, index) {
            $(self.el).append( new CommentListItemView({ model: comment }).render().el );
        });
        return this;
    }
});

Secondly, I am confused about prepending this. 其次,我很担心在this. to something. 某事。 For example in renderComments , why cant I use: 例如,在renderComments ,为什么我不能使用:

var commentList = new CommentCollection();
var self = this;
commentList.fetch({.... });

For the line this.commentList = new CommentCollection(); 对于行this.commentList = new CommentCollection(); , other than instantiating the class CommentCollection() , does it make commentList a child of ModalView ? 除了实例化类CommentCollection() ,它是否使commentList成为ModalView的子ModalView

Additionally, is it necessary to have var self = this; 另外,是否有必要使用var self = this; and use self.commentListView later in the callback function? 并在稍后的回调函数中使用self.commentListView Can binding be used so I can access this.commentListView , or is using var self = this the conventional way of doing things? 可以使用绑定,所以我可以访问this.commentListView ,或者使用var self = this是传统的做事方式吗?

Finally, should self.commentListView = new CommentListView({ collection: self.commentList }); 最后,应该是self.commentListView = new CommentListView({ collection: self.commentList }); in the success function of renderComments be moved to CommentListView 's initialize method instead and be binded to this.collection.on('reset'); renderComments的success函数中,将其移动到CommentListView的initialize方法,并绑定到this.collection.on('reset'); to prevent nesting too many functions? 防止嵌套太多功能? This will result in: 这将导致:

ModalView = Backbone.View.extend({
    el: $('#modal'),

    template: _.template( $('#tpl_modal').html() ),

    initialize: function() {
        _.bindAll(this, 'render', 'renderComments');
        this.render();
        this.renderComments();
    },

    render: function() {
        $(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
    },

    renderComments: function() {
        this.commentList = new CommentCollection();
        this.commentListView = new CommentListView({ collection: this.commentList });
        this.commentList.fetch({
            data: { post_id: this.model.id},
            processData: true
        });
    }
});

CommentListView = Backbone.View.extend({
    el: '.modal_comments',

    initialize: function() {
        this.collection.on('reset', this.render, this);
    },

    render: function() {
        var self = this;
        this.collection.each( function(comment, index) {
            $(self.el).append( new CommentListItemView({ model: comment }).render().el );
        });
        return this;
    }
});

phew--long question(s) ;) phew - 长问题;)

1) I used to do _.bindAll in my initialize methods when I was first using backbone but I have since stopped. 1)当我第一次使用骨干时,我曾经在初始化方法中做_.bindAll但是我已经停止了。 It's not normally needed unless you're binding to events and then it's really helpful. 除非你对事件具有约束力,否则它通常不需要,然后它才真正有用。 For example if you have: 例如,如果你有:

events:
{
    'click': clickHandler
},
clickHandler: function(){
    //do cool stuff
}

then it's helpful to do _.bindAll(this, 'clickHandler') otherwise your this pointer won't be the view 然后执行_.bindAll(this, 'clickHandler')是有帮助的,否则你的this指针将不是视图

2) If i understand your question: commentList becomes a property of your instance of ModalView . 2)如果我理解你的问题: commentList成为你的ModalView实例的ModalView

3) using var self = this; 3)使用var self = this; is relatively common, but in many cases can be avoided because of overloads in Underscore.js (which is a dependency of backbone.js). 相对常见,但在很多情况下可以避免因为Underscore.js中的重载(这是backbone.js的依赖)。 For instance, most of the collection functions ( map , each , etc) take a context as the last parameter. 例如,大多数集合函数( mapeach等)都将上下文作为最后一个参数。 so instead of 而不是

var self = this;
_.map([1,2], function(item){
    self.sum = self.sum + item; 
});

you can do: 你可以做:

_.map([1,2], function(item){
    this.sum = this.sum + item; 
}, this);

if your case you could replace your success method with 如果您的情况可以替换您的success方法

success: _.bind(function() {
             this.commentListView = new CommentListView({ collection: this.commentList });
         }, this);

If you want more info on the somewhat confusing subject of this pointers, it's suggest the following excellent tutorial: http://bonsaiden.github.com/JavaScript-Garden/#function.this 如果你想了解更多关于这个指针有点令人困惑的主题的信息,它建议以下优秀的教程: http//bonsaiden.github.com/JavaScript-Garden/#function.this

4) Yes--I would move the rendering to the reset . 4)是的 - 我会将渲染移动到reset that way if something else causes a reset of the collection the view will pick it up. 这样,如果其他东西导致重置集合,视图将拾取它。

Hope I answered all your questions. 希望我回答你所有的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM