2

我设法使以下代码正确呈现模板。home是一个预编译的模板名称。

app.HomeView = Backbone.View.extend({
  el: '#main',
  template: 'home',
  render: function(){
    var self = this;
    dust.render(this.template, {name:'world'}, function(err,out){
      self.$el.html(out);
    });
    return this;
  }
});

self但是,因为我有很多模板,所以弄乱和灰尘回调的东西并不是很整洁。

是否可以像使用下划线模板一样清理它(如下所示)?

template: _.template( $('#some-template').html() ),
render: function(){
  this.$el.html(this.template( {name:'world'} ));
  return this;
}
4

1 回答 1

1

我实际上并没有使用过灰尘,但是从查看文档来看,似乎没有办法使用上面示例中的回调。self但是,您可以通过使用以下方法将其范围限定为回调方法来摆脱变量bind

render: function(){

  dust.render(this.template, {name:'world'}, function(err,out){
      this.$el.html(out);
  }.bind(this));

  return this;
}

bind不能完全解决您的问题,但无论如何了解它是有用的。请注意,并非所有浏览器都支持它(例如 IE 8)。但是,您可以轻松地将功能添加到不支持它的浏览器。MDN 有一个我使用的不错的小解决方案。

或者,您可以通过使用下划线的内置模板轻松实现您想要的,尽管您必须构建自己的模板缓存来进行模板的预编译。

render: function(){
  this.$el.html(_.template(this.template));
  return this;
}
于 2012-11-27T16:26:39.267 回答