无法获取主干模型提取的结果

Cannot get the result of the Backbone model fetch

本文关键字:提取 结果 模型 获取      更新时间:2023-09-26

我的模型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注释我想在一个又一个音符上做'set'或'get'功能。取回回调函数-成功,但只有我是错误:'Uncaught TypeError:注意。

如果我这样做:'var noteObj = collection.get("0");'我得到了我需要的,但我仍然不能使用get或set。

您应该将urlRoot设置为:

urlRoot: '/notes'

骨干网会计算出它需要将id添加到url中。(文档)

假设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的参数。骨干模型构造函数接受两个参数:attributesoptions (docs),而集合接受modelsoptions (docs)。因此,您需要添加带有id属性的散列作为第一个参数。

还要注意success回调的函数签名。对于一个模型,success回调有三个参数:model, responseoptions (docs)。您将对model参数感兴趣,因为它是获取的主干模型。response为原始响应数据。

我希望我的假设是正确的,这就是你正在寻找的答案。