Backbone Uncaught TypeError:string不是函数

时间:2015-02-25 13:59:40

标签: javascript jquery backbone.js

最近学习Backbone JS。我得到以下错误:我真的不明白出了什么问题,所以请查看下面的错误,并建议我在我的代码中进行必要的更改。

Uncaught TypeError: string is not a function wines.html:56
app.WineView.Backbone.View.extend.render wines.html:56
app.WinesListView.Backbone.View.extend.addOne wines.html:73
(anonymous function) underscore.js:70
h.each.h.forEach underscore.js:103
g.(anonymous function) backbone.js:966
app.WinesListView.Backbone.View.extend.addAll wines.html:69
f backbone.js:208
e.Events.trigger backbone.js:148
i.extend.reset backbone.js:770
t.success backbone.js:865
j jquery.js:3073
k.fireWith jquery.js:3185
x jquery.js:8251
(anonymous function)

这是我的代码:

<div id="header">
    <input type="button" value="New Wine" />
</div>
<div id="sidebar">
    <ul class="wines-list"></ul>
</div>
<div id="content">

</div>

<script type="text/template" id="wine">
    <a href="#wines/<%= id %>">
        <%=n ame %>
    </a>
</script>


<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>


<script type="text/javascript">
var app = {}

app.Wine = Backbone.Model.extend({
    urlRoot: "api/wines",
    defaults: {
        "id": null,
        "name": "",
        "grapes": "",
        "country": "USA",
        "region": "California",
        "year": "",
        "description": "",
        "picture": ""
    }
});

app.WinesList = Backbone.Collection.extend({
    model: app.Wine,
    url: 'api/wines'
});
app.winesList = new app.WinesList();
app.WineView = Backbone.View.extend({
    tagName: 'li',
    template: $('#wine').html(),
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

app.WinesListView = Backbone.View.extend({
    el: '#sidebar',
    initialize: function() {
        this.listenTo(app.winesList, 'reset', this.addAll);

        app.winesList.fetch({
            reset: true
        });
    },
    addAll: function() {
        app.winesList.forEach(this.addOne, this);
    },
    addOne: function(wine) {
        wineView = new app.WineView({
            model: wine
        });
        $('.wines-list').append(wineView.render().el);
    }
});
app.winesListView = new app.WinesListView();
</script>

我已经在谷歌中搜索了这个错误,但在我的案例中并没有理解。

1 个答案:

答案 0 :(得分:1)

在你的wineView模板属性中引用一个元素的内容(所以在这种情况下是一个字符串),然后你试图将它用作函数(因此错误)

尝试将元素传递给下划线模板函数,然后在渲染中使用它,然后传递模型

app.WineView = Backbone.View.extend({
    tagName: 'li',
    template:  _.template($('#wine').html()),
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});