2016-04-15 107 views
0

之后没有更新此流星代码需要根据Session.get('headerLabel')更改headerLabel的值,该值在其他客户端文件中设置时不会更新模板显示。模板助手在session.set

为什么以及如何解决?由于

// client/header.js 
Template.header.helpers({ 
    headerLabel: function() { 
    let userId = Meteor.userId(); 
    if (!userId) { 
     Session.set('headerLabel', 'Please login'); 
    } else { 
     Meteor.subscribe('headerLabel'); 
     let label = HeaderLabelCol.findOne({userId: userId}).headerLabel; 
     Session.set('headerLabel', label); 
    } 
    return {headerLabel: Session.get('headerLabel')}; 
    } 
}); 

// client/lib.js 
utility = (function() { 
    return { 
    toast: function (headerMsg) { 
     const temp = Session.get('headerLabel'); 
     Session.set('headerLabel', headerMsg); 
     setTimeout(() => {Session.set('headerLabel', temp)}, 2000); 
    } 
    } 
}()); 
<template name="header"> 
    <header> 
    <h1 class="main-menu"> 
     <button class="mainMenu" type="button">&#9776;</button> 
    </h1> 
    <h3> 
     <label class="header-label"> 
     {{headerLabel.headerLabel}} 
     </label> 
    </h3> 
    <h1> 
     <button class="subMenu" type="button">&#8942;</button> 
    </h1> 
    </header> 
</template> 

而这会从在客户端的其他一些文件 utility.toast('Wrong entries');

回答

0

辅助函数都应该只取所需的模板数据调用,他们不应该操纵您的应用状态。特别是,您调用的Meteor.subscribe每次模板重新创建时都会创建一个新的订阅句柄。这是一个严重的泄漏。

相反,您应该将您的逻辑代码移动到onCreated,onRenderedonDestroyed方法。

Template.header.onCreated(function() { 
    this.subscribe('headerLabel'); 
    this.autorun(function() { 
    let userId = Meteor.userId(); 
    if (userId) { 
     let label = HeaderLabelCol.findOne({userId: userId}).headerLabel; 
     Session.set('headerLabel', label); 
    } else { 
     Session.set('headerLabel', 'Please login'); 
    } 
    }); 
}); 

Template.header.helpers({ 
    headerLabel: function() { 
    return Session.get('headerLabel'); 
    }, 
});