如何批量分配Backbone模型的所有属性?

JJD*_*JJD 3 attributes model backbone.js

我想在成功的User时候更新模型.它包括后端的分配,之前没有出现在模型中.signInid

MyApp.module("User", function(User, App, Backbone, Marionette, $, _) {

  User.Controller = Backbone.Marionette.Controller.extend({

    initialize: function() {
      this.model = new MyApp.User.Model();
    },

    signIn: function(credentials) {
      var signInData = { user: credentials };
      var self = this;

      App.session.signIn(signInData, {
        success: function(model, response, options) {
          self.updateUserModel(model);
        },
        error: function(model, xhr, options) {}
      });
    },

    updateUserModel: function(model) {
      // TODO Update all attributes, including new onces e.g. id.
    }

  });
});
Run Code Online (Sandbox Code Playgroud)

你会如何一次更新所有的属性?我知道我手动可以使用set每个属性,但这似乎是错误的,因为属性列表可能会随着时间的推移而改变.
一般来说,我希望模型中有这样的update(model)方法User.


当我model.set()按照nikoshr和john-4d5的建议使用Backbone的方法时......

    signIn: function(credentials) {
      var signInData = { user: credentials };
      var self = this;

      App.session.signIn(signInData, {
        success: function(model, response, options) {
          self.model.set(model);
        },
        error: function(model, xhr, options) {}
      });
    },
Run Code Online (Sandbox Code Playgroud)

...该id属性被复制到this.model其他属性中,例如name缺失.

success回调中返回的模型如下所示:

_changing: false
_pending: false
_previousAttributes: Object
attributes: Object
    bind: function (name, callback, context) {
    close: function (){
    constructor: function (){ return parent.apply(this, arguments); }
    created_at: "2013-07-22T19:03:24Z"
    email: "user@example.com"
    id: 3
    initialize: function () {
    listenTo: function (obj, name, callback) {
    listenToOnce: function (obj, name, callback) {
    logout: function () {
    model: child
    name: "Some User"
    off: function (name, callback, context) {
    on: function (name, callback, context) {
    once: function (name, callback, context) {
    options: Object
    signIn: function (credentials) {
    signUp: function (credentials) {
    stopListening: function (obj, name, callback) {
    trigger: function (name) {
    triggerMethod: function (event) {
    unbind: function (name, callback, context) {
    updated_at: "2013-08-05T13:20:43Z"
    user: Object
    __proto__: Object
    changed: Object
cid: "c3"
id: 3
__proto__: Surrogate
Run Code Online (Sandbox Code Playgroud)

nik*_*shr 13

  • 你正在四处走动Backbone.Model,
  • Model.set 接受属性的哈希,
  • 您可以将a转换Backbone.Model为属性的哈希值Model.toJSON

您可以将回调写为

success: function(model, response, options) {
    self.model.set(model.toJSON());
}
Run Code Online (Sandbox Code Playgroud)