質問

I have a model which sets the defaults like so:

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);
    }
});

and in a different model I try and get the models parameters like so:

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

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

        },

Everything seems to run great but when I try to get the "active" param from the CampModel I get the -1 default value and not the value assigned in the model. Any thoughts as to why this happens?

役に立ちましたか?

解決

Model#save is asynchronous, when you're doing:

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

the server hasn't responded yet, so CountActiveAndPending has never been called and active is still -1. Try to log its value in your success callback.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top