سؤال

When I try to save existing object like the below:

this.model.set('name', $('#district-name').val());
this.model.save();

Backbone makes PUT request to /api/districts/18 with data

id: 18
name: "qq3324"

but id is already in url and I don't want to send it in the body of request.

هل كانت مفيدة؟

المحلول

Invoke save with the patch option

Call model.save({ patch: true }) to make a PATCH request including only the changed properties - This affects only the current call to save, so you have to remember to pass the parameter for every call. Also, this mill result in a PATCH request, not in a PUT request.

Write your own implementation of Backbone.sync

Backbone.sync is used by Backbone to communicate with a RESTful API. Overwrite the Backbone.sync method to exclude the ID when making a PUT request - This solution works globally. See the Backbone annotated source for an implementation of this method: http://backbonejs.org/docs/backbone.html#section-130

Overwrite the toJSON method of your model

Backbone.sync calls the model.toJSON method of the model, which is passed an options object (the same options object you give to the model.save function). You can overwrite this function to take a parameter which indicates that the ID should be excluded. This can work globally, if you always extend the BaseModel instead of Backbone.Model.

    var BaseModel = Backbone.Model.extend({
        toJSON: function (options) {
            var data = _.clone(this.attributes);

            if (options.excludeId) {
                data = _.omit(data, 'id');
            }

            return data;
        }
    });

    var SomeModel = BaseModel.extend({});
    new SomeModel({ ... }).save({ excludeId: true });

Or...

Or, just ignore the ID on the serverside.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top