我遇到问题idAttribute导致.save()报告错误的isNew()值,当我想要一个新模型添加到预先填充了ID的服务器时...这导致我保持关闭并设置model.id手动。
这是我的观点:
RecordListItemView = Backbone.View.extend({
initialize:function () {
var record = this.model.attributes;
if (record.user_id) {
this.model.id = parseInt( record.user_id );
record.id = parseInt( record.user_id );
// Added this so ID would show up in model and .attributes
}
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render:function (eventName) {
$(this.el).html(this.template(this.model));
console.log(this);
return this;
}
});
此时我无法使用collection.get(id)检索任何记录,尽管我可以通过collection.getByCid(cid)来完成。
这是我的console.log输出:
d
$el: e.fn.e.init[1]
cid: "view36"
el: HTMLLIElement
model: d
_callbacks: Object
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
id: 15
user_id: "15"
user_name: "Test"
__proto__: Object
changed: Object
cid: "c8"
collection: d
id: 15
__proto__: x
options: Object
__proto__: x
有没有办法修复collection.get(id)而不必更改我的数据库以包含id字段? (目前使用user_id作为pk)
由Benjamin Cox发布如下:(删除了parseInt())
替换
this.model.id = record.user_id;
带
this.model.set({ id: record.user_id });
..避免绕过Model的change事件,而事件又更新了Collection的internal_byId []数组。
经过两次测试后,我使用亩的时间太短parse
建议了。
parse: function(response) {
return {
id: response.user_id,
user_id: response.user_id,
user_name: response.user_name
};
}
答案 0 :(得分:2)
调用collection.get(id)找不到你的模型的原因是当你这样做时你绕过了Backbone的事件机制:
this.model.id = parseInt( record.user_id );
如果你这样做:
this.model.set({ id: parseInt(record.user_id)});
然后模型的set()方法中的Backbone事件代码将触发“change:id”事件。反过来,该集合侦听此事件并更新其内部_byId []数组变量。稍后,当您调用collection.get(id)时,此数组用于搜索匹配的模型。