【问题标题】:how to render dust template simpler with backbone如何使用主干使灰尘模板更简单
【发布时间】:2012-11-27 13:43:51
【问题描述】:

我设法使以下代码正确呈现模板。 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;
}

【问题讨论】:

    标签: backbone.js templating dust.js


    【解决方案1】:

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

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

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

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

    render: function(){
      this.$el.html(_.template(this.template));
      return this;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多