【发布时间】:2013-08-05 10:47:57
【问题描述】:
只要signIn成功,我想更新User 模型。它包括由后端分配的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 每个属性,但这似乎是错误的,因为属性列表可能会随着时间而改变。
一般来说,我希望User 模型中有这样的update(model) 方法。
当我按照 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
【问题讨论】:
-
我可能遗漏了什么,但
this.model.set(model);有什么问题? -
@nikoshr 实际上我在文档中没有看到这一点。我试过了,但它并没有复制其他属性然后
id。例如name在更新的模型中丢失。 -
那么,
model包含什么(成功回调中的第一个参数)?
标签: backbone.js model attributes