我想在成功User
时更新模型。它包括以前模型中不存在的后端分配。signIn
id
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.
}
});
});
您将如何一次更新所有属性?我知道我可以手动set
设置每个属性,但这似乎是错误的,因为属性列表可能会随着时间而改变。
一般来说,我希望模型update(model)
中有这样的方法User
。
当我按照nikoshr和john-4d5的建议使用 Backbone 的model.set()
方法时......
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) {}
});
},
...该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