【问题标题】:Best approach for implementing a reactive button in meteor.js?在meteor.js中实现反应按钮的最佳方法?
【发布时间】:2013-05-03 04:17:19
【问题描述】:

假设我有一个用户可以按下的星号/收藏按钮。如果他们按下它,按钮应该切换状态或看起来不同,并且该状态应该是持久的(如果我刷新页面,它会保持相同的状态)和反应性(假设同一个用户打开了两个浏览器实例并且他们按下了按钮,他们将在其他浏览器中看到新更改的状态 (windw)。

  • 我是否应该在我的车把模板中使用 if 语句在两个不同的 span/div 之间选择不同的按钮?
  • 向该元素添加一个类并为该类的按钮使用不同的 css 并以某种方式将添加的类推回服务器和其他客户端会更好吗?
  • 其他推荐路线?

【问题讨论】:

    标签: javascript css meteor


    【解决方案1】:

    要使其持久化,您需要将其设置在集合中以切换状态

    您的点击处理程序中的 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>
    

    当然以上只是一个示例,您可以使用 each 块助手或不同的模板助手来返回您的数据。但希望你能明白。

    我建议对两个不同的 div 使用 if 语句(您甚至可以只使用 css 类),但我不建议在 html 属性中使用 if 语句或句柄,因为会插入 spark 注释(流星的模板系统)。它们通常是 html cmets,它们在 html 属性中表现不佳。

    【讨论】:

    • 您能否通俗地解释一下这个查询MyCollection.findOne({}).state .state 在做什么? findOne() 搜索匹配,但 .state 在这里是什么意思?
    【解决方案2】:

    你可以使用 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 中:

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

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 2011-07-08
      • 2010-09-09
      • 2018-10-15
      • 2021-10-22
      • 2023-03-17
      相关资源
      最近更新 更多