与backbone.js的模板

时间:2014-02-19 10:51:27

标签: javascript backbone.js

使用backbone.js -

的简单模板

jsTemplateBackbone.html

<html>
<head>
    <script src="jquery-2.1.0.min.js"></script>
    <script src="json2.min.js"></script>
    <script src="underscore.js"></script>
    <script src="backbone.js"></script>
    <!--Order is important !!!--> 
</head>
<body>
        <script type="text/template" id="item-container">
            <li><%= value %></li>
        </script>
        <script src="jsBackboneHomeView.js"></script>
</body>
</html>

jsBackboneHomeView.js

//Model
Wine = Backbone.Model.extend();

// Collection
Wines = Backbone.Collection.extend({
    Model: Wine,
    url: "#"
});
// Collection object
wines = new Wines([
    { name: "Robert Mondovi" },
    { name: "CakeBread" }
]);


// List
ListView = Backbone.View.extend({
    tagName: 'ul',
    initialize: function () {
        // grabing the html template
        this.template = _.template($('#item-container').html());
    },
    render: function () {
        var el = this.$el, template = this.template;
        el.empty();

        wines.each(function (wine) {
            el.append(template(wine.toJSON()));
        });

        return this;
    }
});

// View
HomeView = Backbone.View.extend({
    el: 'body',
    initialize: function () {
        this.render();
    },
    render: function () {
        this.$el.empty();
        this.$el.append("<h1>My App</h1>");
        listView = new ListView();
        // append two <li> on <ul> and return it 
        this.$el.append(this.listView.render().el);

        return this;
    }
});
// View instance
wineApp = new HomeView();

当我执行它时,它会出错 -

Uncaught TypeError: Cannot call method 'replace' of undefined -  underscore.js:1236
line 1236 -  text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {

这里有什么问题?

(代码取自this教程。)

2 个答案:

答案 0 :(得分:2)

模型中的属性在模板中名为name,因此无法替换。试试:

value

在你的模板中。

答案 1 :(得分:0)

在ListView渲染函数中,而不是返回它,返回您想要作为对象使用的值,

e.g。

return({
    el: el
});