JST with Backbone and Underscore

半城伤御伤魂 提交于 2019-12-13 06:08:24

问题


I am using Backbone and Underscore to create a small test site.

I am compiling all my html template files into one JST javascript file as suggested here and here.

It isn't however very obvious how to use this with template files. I have tried this:

App.HeaderView = Backbone.View.extend({
    el: '#headerContent',
    template: JST['header.html'](),
    //template: window["JST"]["header.html"],
    //template: _.template("<h1>Some text</h1>"),

    initialize: function () {
        this.render();
    },

    render: function() {
        //var html = this.template();
        //// Append the result to the view's element.
        //$(this.el).append(html);
        this.$el.html(this.template());
        return this; // enable chained calls
    }
});

The error I get is JST.header.html is not a function.

(The final commented out bit works by the way template: _.template("<h1>Some text</h1>") so I know the problem isn't with anything else).

It might be because I am using browserify (so have tried 'requiring' the file), but I have tried several different ways of 'including' the template file, including adding it directly:

<script src="templates/_templates.js"></script>
<script src="js/functions.js"></script>
</body>
</html>

Any ideas what needs to be done to get this to work?


回答1:


On line 3 you don't want to invoke the template, rather just use:
template: JST['header.html'].

Currently you're setting template to equal the return value of the function and then trying to invoke that return value instead of the actual function, so it is raising a "is not a function" error.



来源:https://stackoverflow.com/questions/29723392/jst-with-backbone-and-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!