backbone 的collection.fetch() 的异步问题

这段代码的:“this.remarks.add(self.model);”在任何函数中始终报出this.remarks是空的。

 app.RemarkEditView = Backbone.View.extend({
    el: '.m-remark' ,
    tagName: 'div',
    className: 'remark',
    template: _.template( $('#remarkEditor').html() ),
    events: {
        'click .save': 'saveRemark',
        'click .del': 'changeEditor'
    },
    initialize: function() {
        var self = this;
        this.remarks = new app.RemarkCollection();
        this.model = new app.Remark({student_id:239, content:'还没有建立评语'});
        this.remarks.fetch();
        this.remarks.add(self.model);
    this.render();  
       this.listenTo(this.remarks, 'add', this.sss );
    },
..................

改成下面这段就好了

app.RemarkEditView = Backbone.View.extend({
    el: '.m-remark' ,
    tagName: 'div',
    className: 'remark',
    template: _.template( $('#remarkEditor').html() ),
    events: {
        'click .save': 'saveRemark',
        'click .del': 'changeEditor'
    },
    initialize: function() {
        var self = this;
        this.remarks = new app.RemarkCollection();
        this.model = new app.Remark({student_id:239, content:'还没有建立评语'});
        this.remarks.fetch({rest:true})
            .done(function(){
                if( self.remarks.length > 0 ){
                    self.model = self.remarks.first();
                }else{
                    self.remarks.add(self.model);
                }
                self.render();
            })
            .fail(function(){
                self.remarks.add(self.model);
                self.render();
            });

        this.listenTo(this.remarks, 'add', this.sss );


    },


.................
    原文作者:taoyh
    原文地址: https://segmentfault.com/a/1190000000404122
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞