2012-05-17 46 views
6

我完全是在挖掘流星,但我一直在試圖減少這些例子的全局性,並添加一些OOP。用coffeescript類包裝meteor.js句柄模板

目前,我的代碼如下所示:

# View for Search Form 
form = Template.SearchForm 
form.events = 
    'submit #search_form' : query_submitted 
    'click #load_more' : -> Songs.get_next_page() 
    'focus #query' : clear_query_field 

form.page = -> Songs.page 
form.total_pages = -> Songs.total_pages 

但是,一拉脊椎或骨幹,我真的很想有是這樣的:

class SearchForm extends Template.SearchForm 
    events: 
    'submit #search_form' : query_submitted 
    'click #load_more' : -> Songs.get_next_page() 
    'focus #query' : clear_query_field 


    page : -> Songs.page 
    total_pages : -> Songs.page 

    # etc etc 

form = new SearchForm 

什麼是正確的方式來包裝流星手柄模板?

我設法包裝Meteor.Collection,但因爲handlebars命名模板後的對象,我不知道正確的方式來做它的模板。

修訂

@格雷格指出,你可以使用_.extend添加的屬性。這很有效,但如果我想將事件處理函數方法'query_submitted'和'clear_query_field'摺疊到類中呢?類似這樣的:

_.extend Template.SearchForm, 
    events : 
    'submit #search_form' : @query_submitted 
    'click #load_more' : -> Songs.get_next_page() 
    'focus #query' : @clear_query_field 

    page : -> Songs.page 
    total_pages : -> Songs.total_pages 

    clear_query_field : (event) -> 
    console.log 'focus' 

    query_submitted : (event) -> 
    event.preventDefault() 
    Songs.clear() 
    Songs.query = $('#query')[0].value 
    Songs.search() 

不太合適。事件處理程序沒有被正確地打來電話,我像控制檯出現錯誤:

Uncaught TypeError: Object [object Window] has no method 'query_submitted'

同樣,

events : 
    'submit #search_form' : (e) -> @query_submitted(e) 

給出:

Uncaught TypeError: Cannot call method 'call' of undefined

所以缺少什麼?

回答

2

流星帶有下劃線,所以你可以:

_.extend Template.SearchForm, 
    events: 
    'submit #search_form' : query_submitted 
    'click #load_more' : -> Songs.get_next_page() 
    'focus #query' : clear_query_field 

    page: -> Songs.page 

    total_pages: -> Songs.page 
+0

謝謝,@greg!我找到了_.extend解決方案,但是我仍然遇到擴展包括事件處理函數的麻煩。我已經更新了這個問題,你會看看嗎? –

1

您是否嘗試過與Template.Searchform代替@。在你的事件綁定?

+0

這工作,如果你先用處理程序擴展,然後與該事件定義再次擴展: '_.extend Template.SearchForm, clear_query_field:(事件) - >腳本非常重要 _.extend Template.SearchForm 事件: 'focus #query':clear_query_field ... ' –

+0

@ScottSimon您可以提供關於您的發現的原始問題的更新。 TKS –