繁体   English   中英

与backbone.js的模板

[英]Template with 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) {

这有什么不对?

(从教程中获取的代码。)

模型中的属性称为name而它在模板中是value ,因此无法替换。 试试:

<li><%= name %></li>

在你的模板中。

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

例如

return({
    el: el
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM