使用带有骨干的把手

时间:2012-01-30 23:24:38

标签: backbone.js requirejs handlebars.js

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

4 个答案:

答案 0 :(得分: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 );
    }
});

基本上,骨干的约定是在渲染函数中构建你的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 );
    }
});

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

答案 1 :(得分:2)

我更喜欢编译模板一次(在初始化期间),这样就可以避免在每次渲染时重新编译模板。此外,您需要将模型传递给编译模板才能生成HTML:

SearchView = Backbone.View.extend({
  initialize: function(){
    // Compile the template just once
    this.template = Handlebars.compile($("#search_template").html());
    this.render();
  },
  render: function(){
    // Render the HTML from the template
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

答案 2 :(得分:1)

如果您使用的是require.js,则无法使用当前的Handlebars文件。我使用了以下Handlebars Plugin,它似乎与当前版本保持同步。如果Handlebars在模块中返回null,只需用上面的插件替换Handlebars文件即可。

答案 3 :(得分:0)

define(["app", "handlebars",
    "text!apps/templates/menu.tpl"
], function (app, Handlebars, template) {

    return {
        index: Marionette.ItemView.extend({
            template: Handlebars.compile(template),
            events: {
                'click .admin-menu-ref': 'goToMenuItem'
            },
            goToMenuItem: function (e) {
               //......
            }
        })
    }
});


 new view.index({model: models});