简体   繁体   中英

Resetting backbone.js attributes hash

I've created a model in backbone:

var app={};
app.pilot_id = $("#user_id").val();   
app.Pilot = Backbone.Model.extend({    
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/',   
sync: function(method, model, options) {
    return Backbone.sync(method, this, $.extend(options, {
     beforeSend: function (xhr) {
       xhr.setRequestHeader ('X-WP-NONCE', POST_SUBMITTER.nonce);
     }
  }))   
},
defaults : {
    lastName: 'Doe', 
    firstName: 'John'
},
initialize : function() {
  this.fetch({ data: ({id: app.pilot_id})});
 }
});

app.pilot = new app.Pilot(); { after the fetch lastName will be 'Smith' and firstName will be 'Sue'

and I create a view with backform.js

app.PilotForm =  Backform.Form.extend({
el: $("#personalInformation"),
events: {
    "submit": function(e) {
    e.preventDefault();this.model.save( {patch: true})
    .done(function(req, status, err) {
        alert( status + ', ' + err);
        console.log(status, err);
    })  
    .fail(function(req, status, err) {
        alert( status + ', ' + err);
    });
      return false;
    }
 },
 fields: [
   {name: "id", label: "Id", control: "uneditable-input"},
   {name: "firstName", label: "First Name", control: "input"},
   {name: "lastName", label: "Last Name", control: "input"},
   {control: "button", label: "Save to server"}
 ],});
  new app.PilotForm({model: app.pilot}).render();

This is going to be a multi-page form. And only a few fields will need to be updated each time. So I would like to update the server with "PATCH" However ALL of the fields that have been pre-filled from the fetch are flagged at changed. Therefore everything is sent in the PATCH request.

After creating the new app.PilotForm... I've added

app.pilot.attributes={};  

This does work; now when I change a field only that field is sent in the PATCH request. However, the documentation suggests it is bad to mess directly with the attributes hash. Is there a better way to do this?

You can use model method such as changedAttributes , previousAttributes etc to find the info you want to send to the server and then use that patch option of model.save :

If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}) . You'll get an HTTP PATCH request to the server with just the passed-in attributes.

Where attrs is whatever you want to be the payload

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