Backbone 使用 Underscore 的诱惑是在模板中呈现一个属性而不是另一个

Backbone Tempting with Underscore is rendering one attribute in template but not the other

我正试图在 Backbone 中制作一个简单的列表,但 运行 遇到了一个奇怪的问题。这是我第一次使用下划线模板,所以我不确定这是否是原因。看起来这是一个简单的问题,但我无法弄清楚。

我有一个 backbone 模型,其属性为 nameband。当我只让它渲染 name 时,如下所示,它成功渲染了名称列表。

var template = _.template("<h2><%= name %></h2><br><h3></h3>")

渲染效果很好。但是当我对 band 变量进行任何迭代时,它会抛出错误 Uncaught ReferenceError: band is not defined,我不明白为什么。它从我传递给它的属性对象中获取名称的引用。为什么它看到 name 而不是 band

完整代码如下。

var Album = Backbone.Model.extend({
    defaults: {name: "The Album", band: "The Band"}
});
var albumOne = new Album({name: "SGT PEPPER", band: "The Beatles"});
//Eight more album instances here

var template = _.template("<h2><%= name %></h2><br><h3><%=band%></h3>")

var AlbumCollection = Backbone.Collection.extend({
    model: Album,
    initialize: function(){
        this.render()           
    },
    render: function(){
        this.each(function(item){
            new tempView(item);
        });
    }
});
var tempView = Backbone.View.extend({
    tagName: 'li',

    template: template(),

    initialize: function(){
        this.render();
    },
    el: $("#shuff"),
    render: function(){ 
        this.$el.append(template(this.attributes))
    }
});

window.myCollection = new AlbumCollection([albumOne, albumTwo, albumThree, albumFour,albumFive,albumSix,albumSeven,albumEight,albumNine]);
window.myCollection.render();

断点不是你的render方法,而是template属性。

您正在使用 template: template() 分配评估模板,但在全局上下文 (window.band) 上没有 band,并且评估中断。它仅适用于 name 变量,因为 window.name is in fact a valid property.

试试 template: template 你的例子会 运行 http://jsfiddle.net/nikoshr/6j58kf2w/

注意:我必须补充一点,混合模型和视图可能会导致无法预料的问题。我建议尽量让模型对视图一无所知。