下划线模板在骨干网中不起作用

时间:2013-10-22 07:16:13

标签: backbone.js underscore.js

在我view.js我正在调用wine-list-tpl(模板),如下所示,你可以看到这一点。但是没有任何东西显示在索引页面上。请帮忙。

IN index.html

<script type="text/template" id="wine-list-tpl">
Hello world 
<%= name %>
</script>
.......
<div class="wine-list"></div>

在view.js

var WineLists = Backbone.View.extend({

el:'.wine-list',

template : _.template($('#wine-list-tpl').html()),

render: function(){
    console.log("rendering is ok");
    this.$el.html( this.template( this.model.toJSON() ));
    return this;
    }
}); 

var WineList = Backbone.View.extend({
model:wines,

initialize: function(){ 
    var self=this;
    wines.fetch();
    _.each(this.model.toArray(), function(wine, i){

        $('#wine-list').append((new WineLists({ model : wine })).render().$el);

        });
    }
});

var wineListView = new WineList();

我已将一些数据添加到我的本地存储中,我只想将这些数据显示给该特定的div元素。

在WineLists视图中,我获取所有这些数据。表示我在写作时,console.log(this.model.get('name'));我得到了我想要的数据,但我只想通过模板向那个特定的div显示这些数据。我该怎么办,请建议。

2 个答案:

答案 0 :(得分:0)

这就是您的代码应该如何获得预期结果。

var WineLists = Backbone.View.extend({
    el: '.wine-list',
    render: function () {
        var _self = this;
        this.collection.each(function (model) {
            var view = new WineListItemView({
                model: model
            })
            view.render();
            view.$el.appendTo(_self.el);
        })
        return this;
    }
});



var WineListItemView = Backbone.View.extend({
    template: _.template($('#wine-list-tpl').html()),
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

var wines = new Backbone.Collection([{
    name: 'wine1'
}, {
    name: 'wine2'
}])
var wineListView = new WineLists({
    collection: wines
});
wineListView.render()

答案 1 :(得分:0)

var WineLists = Backbone.View.extend({

model: new Wine(),

template : _.template($('#myTpl').html()),

render: function(){
//console.log(this.model.get('name'));
this.$el.html(this.template(this.model.toJSON()));
return this;
} });   

var WineList = Backbone.View.extend({
model:wines,
el:'.wineDiv',
initialize: function(){ 
var self=this;
wines.fetch();
_.each(this.model.toArray(), function(wine, i){

self.$el.append((new WineLists({ model : wine })).render().$el);

});}});

var wineListView = new WineList();


//please check ur DOM manipulation i think there is some error in ur HTML try to change call //sequence