简体   繁体   中英

Backbone.js model.fetch when server data is empty

I have an app where we are using model.fetch() to pull JSON from the server, and we have this as our render function that fires when the model changes:

if(_.isUndefined(this.model.get("id_number"))){
    this.template = initialTemplate;
} else if(this.model.get("id_number") == 0) {
    this.template = templateA;
} else {
    this.template = templateB;
}
return BaseView.prototype.render.call(this);

On pageload, we don't do model.fetch() yet and get the initialTemplate. When a user changes an input, we fetch and get new model data that can have an ID of 0 or something else.

Now there is also a chance the server JSON might change to an empty {} and if so we need to revert to showing the initialTemplate. The problem is it appears that if that's the case, model.fetch() doesn't return anything and nothing changes. Same thing if id_number is undefined. (It does work if it's null.)

Is there a solution so Backbone will fetch an empty data set?

The solution for this was something Stephen mentioned: a success function. I added this to the model.fetch() function:

success: function(model, response /*jshint unused: false */) {
    if (_.isEmpty(response)) {
        view.model.set("id_number", undefined);
    }
},...

FYI to anyone who uses this in the future: Backbone won't let you pass only response to the function because it expects model first. You can pass model and not use it, but you'll need the comment above to pass JSHint.

Set defaults in your model

Here is documentation. http://backbonejs.org/#Model-defaults

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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