【问题标题】:Backbone Tempting with Underscore is rendering one attribute in template but not the otherBackbone Tempting with Underscore 在模板中渲染一个属性,而不是另一个
【发布时间】:2015-09-18 06:10:52
【问题描述】:

我正在尝试在 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();

【问题讨论】:

    标签: javascript backbone.js underscore.js


    【解决方案1】:

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

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

    尝试template: template,您的示例将运行http://jsfiddle.net/nikoshr/6j58kf2w/

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      相关资源
      最近更新 更多