【问题标题】:on load function when subscription ready on Meteor Blaze?在 Meteor Blaze 上订阅准备就绪时加载功能?
【发布时间】:2017-12-02 20:39:28
【问题描述】:

我在我的项目中使用 Meteor 和 blaze,我想在 Meteor 模板中调用 JavaScript 函数。更准确地说,我当然使用了发布者订阅者,但是当我订阅以从 mongo DB 中检索信息时,我希望触发一个函数。

事实上,我检索数据,但它处理“真”或“假”之类的行数据,我想根据数据结果调用一个影响不同属性的函数。

例如,如果我的 db 的元素设置为“true”,当订阅准备就绪时(或在我的页面加载后),它将用绿色矩形替换“true”。

为此,我想知道我们是否可以使用

Template.devicesConfiguration.onCreated(function(){
var self = this;
self.autorun(function(){
    self.subscribe('Buttons');

    //call a javascript function that uses the result of the db

    });
});

或在

Template.devicesConfiguration.helpers({
    buttons:()=>{   

        //call a javascript function that uses the result of the db

        return ButtonsCollection.find({}); 

    }

});

甚至是一种方法?

有人有想法吗?多谢 !

【问题讨论】:

    标签: javascript templates meteor meteor-blaze


    【解决方案1】:

    我会选择订阅,然后是简单的辅助函数:

    Template.devicesConfiguration.onCreated(function () {
        Meteor.subscribe('Buttons'); // Subscribe to your buttons
    });
    
    Template.devicesConfiguration.helpers({
        // Will return a "transformed" array of all the Buttons in collection
        buttons(){
            return ButtonsCollection.find({}) // Find all buttons
                                    .map(button => {
                                        // Do something with button object
                                        // Like check true / false and change rectangle color
                                    })
        }
    });
    

    我只是订阅模板创建的数据。

    然后我注册一个buttonshelper,它从集合中返回数据,但在返回之前对数据执行转换(映射函数)。

    然后您可以在模板中使用{{#each button in buttons}} 来循环数据并显示每个按钮。

    【讨论】:

    • 我尝试这样做但是错误,我猜语法不正确但我理解这个想法。这里是模板助手的代码:buttons:()=>{ return ButtonsCollection.find({}).map(button=>{ var buttonValue = ButtonsCollection.find({},{fields:{value:"true"}}).fetch(); var CheckButtonsLed = document.getElementsByClassName("CheckButtonsLed"); for(i=0;i<buttonValue.length;i++){ CheckButtonsLed[i].style.backgroundColor="green"; } }); } 然后我使用了 {{#each button in buttons}}。 (我的按钮集合有 2 个属性:名称和值)
    【解决方案2】:
    Template.devicesConfiguration.helpers({
        buttons() {
            return ButtonsCollection.find({}).map(button => {
                if(button.value === true) button.className = 'green';
                else button.className = 'red'; 
            })
        }
    });
    

    在模板中类似于:

    {{#each button in buttons}}
        <button class={button.className}>{button.name}</button>
    {{/each}}
    

    已经有一段时间没有写任何 Blaze 了,但我希望你能明白。

    【讨论】:

    • 感谢您的回答,我理解这个想法:) 我试图实现它。它可以工作,但无论我使用{{button name}}{{button.name}}{{name}}{button name}{button.name}{name},车把都不会显示我的按钮属性。但是,助手部分有效,例如,我可以根据 if 循环中的值声明 console.log(button.name + button.value)
    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    相关资源
    最近更新 更多