我的模型 urlRoot:
urlRoot: function() {
if (this.id != null ) {
return 'notes/' + this.id;
} else return 'notes';
}
功能:
window.show_note = function (note_id) {
var note = new Memo.Models.Note([], { id: note_id });
note.fetch({
success: function (collection, note, response) {
var noteObj = collection.get("0");
var noteView = new Memo.Views.FullNote( {model: noteObj }, {flag: 0 } );
$('.content').html(noteView.render().el);
}
});}
{ id: note_id } - 我将其发布到服务器以通过 id 获取注释 我想在回调函数中的 note.fetch 之后对模型“note”执行“set”或“get”功能 - 成功,但只有我有错误:“Uncaught TypeError: note.set is not a function”。
如果我这样做:'var noteObj = collection.get("0");' 我得到了我需要的,但我仍然不能使用 get 或 set。
最佳答案
您应该将 urlRoot
设置为:
urlRoot: '/notes'
backbone 会发现它需要将 id
添加到 url。 ( docs )
假设 Memo.Models.Note
是一个模型而不是一个集合,上面的代码片段应该是这样的:
window.show_note = function(note_id) {
var note = new Memo.Models.Note({ id: note_id });
note.fetch({
success: function (model, response, options) {
var noteView = new Memo.Views.FullNote({
model: model
}, {flag: 0 });
$('.content').html(noteView.render().el);
}
});
};
注意传递给 new Memo.Models.Note
的参数。主干模型构造函数有两个参数:attributes
和 options
( docs ) 而集合则有 models
和 选项
( docs )。因此,您需要添加带有 id
属性的散列作为第一个参数。
还要注意 success
回调的函数签名。对于模型,success
回调采用三个参数:model
、response
和 options
( docs )。您会对 model
参数感兴趣,因为这是获取的 Backbone 模型。 response
是原始响应数据。
我希望我的假设是正确的,这就是您正在寻找的答案。
关于javascript - 无法获取 Backbone 模型提取的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33019292/