Javascript 在meteor.js中实现被动按钮的最佳方法?

Javascript 在meteor.js中实现被动按钮的最佳方法?,javascript,css,meteor,Javascript,Css,Meteor,假设我有一个星型/收藏夹按钮,用户可以按下它。如果他们按下该按钮,则该按钮应切换状态或看起来不同,并且该状态应为持久状态(如果我刷新页面,则其保持相同状态)和反应状态(假设同一用户打开了两个浏览器实例,并且他们按下该按钮,则他们将在另一个浏览器windw中看到新更改的状态) 我应该在我的把手模板中使用if语句,在两个不同的跨距/div之间使用不同的按钮进行选择吗 将一个类添加到该元素中,并对该类的按钮使用不同的css,然后将添加的类推回到服务器和其他客户端,这样会更好吗 还有其他推荐路线吗 要

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

  • 我应该在我的把手模板中使用if语句,在两个不同的跨距/div之间使用不同的按钮进行选择吗
  • 将一个类添加到该元素中,并对该类的按钮使用不同的css,然后将添加的类推回到服务器和其他客户端,这样会更好吗
  • 还有其他推荐路线吗

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

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

{{{#如果你的模板是.state}
国家1
{{else}
州0
{{/if}
当然,上面只是一个示例,您可以使用每个块辅助对象或不同的模板辅助对象来返回数据。但希望你能明白


我建议对两个不同的div使用if语句(您甚至可以只使用css类),但我不建议在html属性中使用if语句或手柄,因为spark注释(meteor的模板系统)是内置的。它们通常是html注释,在html属性中发挥得不太好。

您可以使用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>

{{{#如果按钮_状态}
国家1
{{else}
州0
{{/if}

请您用外行的语言解释一下,在这个查询中,
MyCollection.findOne({}).state
.state
在做什么
findOne()
搜索匹配项,但是
.state
在这里意味着什么?