从一个模型到另一个模型的引用var在Backbone中返回默认值



我有一个设置默认值的模型,如下所示:

var CampModel = Backbone.Model.extend({
    defaults: {
        siteID: $.jStorage.get('currentSiteID'),
        active: -1,
        pending: -1,
    },
    url: function () {
        //some url.
    },
    sync: function (method, model, options) {
        var method = 'read';
        var that = this,
        options = options || {};
     options.success = function(model, response, options){
       if(response.errorMessage != "Session is over")
        console.log('Update session');
    if(response.success)
        if(response.returnValue.length){
            that.set('response', response.returnValue);
            that.CountActiveAndPending(response.returnValue);
        }
        else {
            that.set('response', []);
        }
        else console.log('report: bad request, error: '+ response.errorMessage);
    }
    Backbone.sync(method, model, options);
},
    },
    //Counts active and pending campaigns for front page.
    CountActiveAndPending: function (data) {
        var active = 0;
        var pending = 0;
        //var it = this;
        $.each(data, function (index, val) {
            if (val.ApprovedOnSite) active++;
            else pending++;
        });
        this.set('active', active);
        this.set('pending', pending);
    }
});

在另一个模型中,我尝试获得模型参数,比如:

 this.set({
            campModel: new CampModel(),
            })
          });
            this.get('campModel').save();
           console.log(this.get('campModel').get('active'));
        },

一切似乎都运行得很好,但当我试图从CampModel中获取"活动"参数时,我得到的是-1默认值,而不是模型中分配的值。有没有想过为什么会发生这种事?

Model#save是异步的,当您执行以下操作时:

console.log(this.get('campModel').get('active'));

服务器还没有响应,所以CountActiveAndPending从未被调用,active仍然是-1。尝试将其值记录在success回调中。

相关内容

  • 没有找到相关文章

最新更新