2011-09-03 72 views
25

我已經踢Backbone.js的的輪胎,並在最近幾周圍繞具有玩,所以有點小白問題......Backbone.js - 在哪裏定義視圖助手?

什麼是「正確」的方式來定義和使用視圖助手Backbone.js的?

據我所知,定義幫助程序在模板中使用的唯一真實位置在模型或集合本身上。但是,當該幫助程序直接返回HTML時,這會變得有點骯髒。

有沒有更好的方法?

回答

41

有,我把視圖助手與Backbone.js的幾個不同的地方:

如果助手是具體到某個視圖,把它放在右視圖定義:

var MyView = Backbone.View.extend({ 
    tagName: 'div', 

    events: { 
    ... 
    }, 

    initialize: function() { ... }, 

    helperOne: function() { 
    // Helper code 
    }, 

    anotherHelper: function() { 
    // Helper code 
    }, 

    render: function() { 
    ... this.helperOne() ... 
    } 
}); 

如果助手將所有視圖中使用,擴展骨幹視圖類,以便所有視圖繼承了這一功能:

_.extend(Backbone.View.prototype, { 
    helper: function() { 
    // Helper code 
    } 
} 

如果您需要視圖之間傭工更復雜的共享,有觀點相互延伸:

var MyOtherView = MyView.extend({ 

    // ... 

    render: function() { 
    ... this.helperOne() ... 
    } 
}); 

我不知道什麼是最好的做法(或者,如果有一個既定的最佳做法),但這些模式看起來相當乾淨並且運作良好。

+1

也可以做混入(即根據需要從類集合中獲得類「mixin」),甚至是面向方面的編程(具有單個函數調用覆蓋類的集合,用另一種方法包裝目標方法)。 –

+2

+1用於擴展Backbone View類 – isNaN1247

+1

嗯,在'extend'內使用'this'對我來說不起作用,但'this .__ proto__'確實有效。不應該'__proto__'方法只用'this'來工作?例如'this.myMethod()'而不是'this.__ proto __。myMethod()'。對我來說,後者有效,但前者失敗。 –

0

當你構建更大的Backbone應用程序時,你可能想要命名空間的一切。那麼你將有一個全球幫手的地方。我還沒有完成完美的命名空間設置。但現在我在做這樣的事情:

brainswap:{ 
    appView: {},   <== Reference to instantiated AppView class. 
    classes = {   <== Namespace for all custom Backbone classes. 
    views : {}, 
    models : {}, 
    collections: {}, 
    controllers : {}, 
    Router: null 
    }, 
    models: {},   <== Instantiated models. 
    controllers: {},  <== Instantiated controllers. 
    router: {},   <== Instantiated routers. 
    helpers: {},   <== Reusable helper platform methods. 
    currentView: {},  <== A reference to the current view so that we can destroy it. 
    init: function(){} <== Bootstrap code to start app. 
} 

我的視圖類是這個樣子:

brainswap.classes.views.profile.contact = brainswap.classes.views.profile.base.extend({... 

我的控制器是一個新實例化視圖(和放在currentView的參考對象。記住,你應該總是刪除您上次查看所以以前的看法事件都得到unbinded和你減少內存使用。

0

快速解決方案(CoffeeScript的)

Backbone.View::handlebarsTemplate = (templateName) -> 
    Handlebars.compile $(templateName).html() 

然後你可以使用在你的觀點:

Yourcoolapp.Views.ThingsIndex extends Backbone.view 

    initialize: -> 
    @template = this.handlebarsTemplate("#hb_template") 
    # etc... 

    someMethod: => 
    @template = this.handlebarsTemplate("#hb_other")