2014-02-26 31 views
0

这是我尝试加载widget.tpl时简单的BackboneView。 但是模板var包含一个函数()骨干的handlebars和requirejs:handlebars返回一个函数,而不是html

我该怎么做错?

define(['hbs!templates/widget'],function (template) { 
var template = Handlebars.compile(template); 
console.log(template); 

MyView = Backbone.View.extend({ 
    initialize: function(){ 
     this.render(); 
    }, 
    render: function(){ 
     // Compile the template using Handlebars 

     console.log(template); 
     //this.el.html(template); 
    } 
}); 
    return MyView; 
}); 

widget.tpl具有

<div>helloworld</div> 
+0

是不是标准的行为?尝试'console.log(template())'。 – Puigcerber

+3

'Handlebars.compile'将带有占位符的模板转换为可以使用占位符参数执行的函数,以获取所需的HTML。 – Cyclone

+0

我的回答有帮助,还是需要帮助? – bejonbee

回答

1

注意不要重新定义template变量。 hbs插件返回已编译的Handlebars函数as you can see in the docs。它可能会是这样更好:

define(['hbs!templates/widget'],function (template) { 
    console.log(template); // -> logs compiled Handlebars template function 

    var MyView = Backbone.View.extend({ 
     render: function(){ 
      // Compile the template using Handlebars 
      this.$el.append(template()); 
      return this; 
     } 
    }); 
    return MyView; 
}); 

而且,你可能不希望渲染初始化视图。初始化应该只设置你的视图;在初始化时渲染会在创建实例时引入不需要的副作用。在你的代码中的其他地方你会得到这个:

var MyView = require('MyView'); 
var view = new MyView(); 
$('body').append(view.render().el); 
相关问题