forste
forste

Reputation: 1133

Backbone - boostrap data with isNew attribute set to false

I'm using backbone and bootstrapping some data according to practice (http://documentcloud.github.com/backbone/#FAQ-bootstrap).

However, now when I save any bootstrapped model, the Backbone treats the model as non-existent on the server (model.isNew === true, http://backbonejs.org/#Model-isNew) which in turn calls Backbone.sync with method 'create' instead of 'update'. Thus, the POST instead of the PUT HTTP method is called.

how can I have bootstrapped models with isNew set to false, i.e. backbone treating them as existent on the server?

Upvotes: 2

Views: 1750

Answers (2)

forste
forste

Reputation: 1133

Apparently, model.isNew is determined by whether the id is set as explained here: http://backbonejs.org/#Model-isNew. That means bootstrapping data with the id set solves my problem

Upvotes: 2

bazwilliams
bazwilliams

Reputation: 330

I encountered this problem recently, I overcame by overriding the parse(), initialize() and isNew() functions in my Backbone model.

The initialize() function initialises a 'loadedFromServer' property to false.

    initialize: function () {
        this.loadedFromServer = false;
    },

The parse() function sets the 'loadedFromServer' property to true and returns the response:

    parse: function (response) {
        this.loadedFromServer = true;
        return response;
    },

The isNew() function then checks the id (for blank models) or whether the id has been set, but not synced to server:

    isNew: function () {
        return !this.id || !this.loadedFromServer;
    }

This satisfies the following tests:

isNew() reports false when fetched isNew() reports true when no id has been set isNew() reports true when an id has been set (for PUT), but was never fetched

Upvotes: 0

Related Questions