Backbone Model Save:将字段作为“模型”子对象发送

时间:2013-09-06 00:20:41

标签: javascript backbone.js model backbone-model

用户模型

define(
  [
    'backbone'
  ],
  function (Backbone) {

    return Backbone.Model.extend({
      url: '/proxy.php/users.json',

      defaults: {
        'first_name': '',
        'last_name': '',
        'work_email': ''
      },

      validation: {
        first_name: {
          required: true,
          msg: 'Please enter a first name'
        },

        last_name: {
          required: true,
          msg: 'Please enter a last name'
        },

        work_email: {
          required: true,
          msg: 'Please enter a valid email'
        }
      }

    });
  }
);

查看保存数据

  onSave: function (ev) {

    ev.preventDefault()

    var details = $('.edit-user-form').serializeObject()
    var object = new User()

    return object.save(details, {
      success: function (response) {
        console.log(response, 'response')
      }
    })
  },

details =

{first_name: "", last_name: "", birthdate: "", job_title: "", job_start_date: ""…}
birthdate: ""
first_name: ""
job_probation_ends: ""
job_start_date: ""
job_title: ""
last_name: ""
personal_address: ""
personal_email: ""
personal_phone_number: ""
work_address: ""
work_email: ""
work_phone_number: ""

问题是,Backbone发送的请求将表单数据发送为:

model:{"first_name":"","last_name":"","work_email":"","birthdate":"","job_title":"","job_start_date":"","job_probation_ends":"","work_address":"","work_phone_number":"","personal_email":"","personal_address":"","personal_phone_number":""}

为什么将属性作为模型的子对象?我希望以root身份发送属性。

1 个答案:

答案 0 :(得分:0)

如果要修改发送到服务器的数据的结构,请覆盖模型的toJSON方法:

toJSON: function () {
    return { // structure the model as you wish here };
}