使用带有骨干的把手

Jos*_*ter 49 requirejs backbone.js handlebars.js

我正在学习Backbone/Handlebars/Require.我已经在网上查看了所有内容 - 是否有任何可以指导我的教程或网站,这将为使用把手而不是下划线提供有用的信息?

Sim*_*lGy 79

使用handlebars.js代替下划线模板是非常简单的.看看这个例子:

https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-view (滚动到"加载模板"部分)

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), {} );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});
Run Code Online (Sandbox Code Playgroud)

基本上,骨干的约定是在渲染函数中构建你的html.模板引擎的使用完全取决于你(我喜欢Backbone).所以你只需将其改为......

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using Handlebars
        var template = Handlebars.compile( $("#search_template").html() );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});
Run Code Online (Sandbox Code Playgroud)

由于您使用的是require.js,因此您可以将Handlebars作为模块顶部的依赖项.我对此很陌生,但听起来重点关注的是Backbone.js模式和require.js用法.

  • 当使用`Backbone.Model`或`Backbone.Collection`作为模板上下文时,记得使用[`.toJSON()`](http://backbonejs.org/#Model-toJSON) (2认同)