2012-11-27 46 views
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; 
} 

回答

1

我還沒有實際使用的灰塵,但看着the docs它看起來像有在你的周圍例如使用一個回調像上面沒有辦法。你可以,但是,擺脫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有我使用的nice little solution

或者,您可以使用下劃線的內置模板來輕鬆實現您想要的內容,但承認您必須構建自己的模板緩存以進行模板的預編譯。

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

感謝您指出'bind'。 –