2013-05-08 37 views
2

比方說,我有一個可以由用戶按下的明星/收藏夾按鈕。如果他們按下按鈕應該切換狀態或看起來不同,並且狀態應該是持久的(如果我刷新頁面它保留相同的狀態)和反應性(假設同一用戶有兩個瀏覽器實例打開,他們按下按鈕,他們會在另一個瀏覽器中看到新改變的狀態)。在meteor.js中實現響應按鈕的最佳方法是什麼?

  • 我應該在我的車把模板中使用if語句來選擇兩個具有不同不同按鈕的不同跨度/ div的if語句嗎?
  • 最好是向該元素添加一個類,併爲該類的按鈕使用不同的css,並且有人將添加的類推回服務器和其他客戶端?
  • 其他推薦路線?

回答

5

因爲這是持久性的,你就需要設置一個集合中,以切換狀態

你的JS在你的點擊處理程序:

Template.yourtemplate.events({ 
    'click #yourbutton':function(event,template) { 
     var state = MyCollection.findOne({}).state 
     MyCollection.update({}, {$set:{state:!state}}); 
    } 
}); 

Template.yourtemplate.helpers({ 
    item:function() { 
     return MyCollection.findOne({}); 
    } 
}); 

那麼你的HTML:

<template name="yourtemplate"> 
    {{#if yourtemplate.state}} 
     <div id="yourbutton">STATE 1</div> 
    {{else}} 
     <div id="yourbutton">STATE 0</div> 
    {{/if}} 
</template> 

當然,以上只是一個示例,您可以使用每個塊幫助程序或不同的模板幫助程序來返回您的數據。但希望你明白這個主意。

我會推薦使用兩個不同div的if語句(你甚至可以只使用css類),但我不會推薦使用if語句或html屬性中的句柄,因爲spark標註(流星的模板系統)放入它們通常是html的註釋,並且它們在html屬性中的表現並不好。

+0

的作品就像一個夢 – funkyeah 2013-05-09 05:44:36

+0

能否請您解釋一下({} ).state'' .state'在做什麼? 'findOne()'搜索匹配,但是'.state'在這裏意味着什麼? – Edgar 2016-02-25 23:38:59

0

你可以使用一個ReactiveVar:

Template.yourtemplate.onCreated(function() { 
    this.buttonState = new ReactiveVar(); 
    this.buttonState.set(true); 
}); 

Template.yourtemplate.events({ 
    'click #yourbutton'(event,tmpl) { 
     var state = tmpl.buttonState.get(); 
     tmpl.buttonState.set(!state); 
    } 
}); 

Template.yourtemplate.helpers({ 
    button_state() { 
     const tmpl = Template.instance(); 
     return tmpl.expandedState.get(); 
    } 
}); 

而在HTML:通俗地說是什麼在此查詢`MyCollection.findOne

<template name="yourtemplate"> 
    {{#if button_state}} 
     <div id="yourbutton">STATE 1</div> 
    {{else}} 
     <div id="yourbutton">STATE 0</div> 
    {{/if}} 
</template> 
相關問題