【问题标题】:Why is my template helper that uses session.get not reactive?为什么我使用 session.get 的模板助手不是响应式的?
【发布时间】:2015-11-08 06:12:24
【问题描述】:

在我的客户端代码中,我有一个 Session,它被设置为全局函数中的一个对象:

somefunctions.js

updateTimelineItem = function(newSelection){
    var selectedItem = $.grep(Session.get('liveProjectData').items,function(e){return e.position ==newSelection.parent().index()});
    Session.set('selectedItem',selectedItem[0]);
};

但是,在我需要显示此会话的部分对象数据的模板文件中,我的助手在会话设置后不会触发。

mytemplate.js

Template.mytemplate.helpers({    
    selectedItem: function(){
        console.log('reactive update. new item selected.');
        return Session.get('selectedItem');
    }
})

会话存储的示例

Object { position: 0, type: "image", source: "imgur", source-url: "https://dl.dropboxusercontent.com/u…", provider: "magic", animation: "puff", thumb: "https://dl.dropboxusercontent.com/u…", fullsize: "https://dl.dropboxusercontent.com/u…", duration: 1000 }

我试图找到有关如果没有太多运气 Session 何时不会反应的文档。我知道会话已设置,因为我可以在浏览器控制台中编写 Session.get('selectedItem') 并获得预期的输出。

感谢您的帮助。

【问题讨论】:

  • Session 将序列化其输入,这在存储复杂数据时通常会导致异常行为。你能举例说明selectedItem[0] 的样子吗?
  • 谢谢大卫,我已经在我的问题中放置了我存储在会话中的数据的示例。
  • 您可能想在大卫建议的设置/获取会话变量之前/之后JSON.stringify/JSON.parse您的对象
  • 我现在尝试将会话设置为一个简单的字符串,但反应式代码仍然无法运行。如果 Session.set(...) 出现在相同的模板代码中,是否可能仅将 template.helpers 视为反应式计算?我从全局函数调用 set 因为多个模板访问它(因为 UI 的多个部分可以触发它)。
  • 不,set 和 get 可以在不同的计算中。这是 Meteor 中反应式编程的一部分。

标签: javascript meteor


【解决方案1】:

我的反应式代码没有运行的原因是我没有访问该模板空格键中的特定反应式变量。尽管 Template.helpers 是一种反应式计算,但它基于 dom 中反应式变量的使用来执行。这与其他反应式计算不同。

这方面的信息很难获得,但在 Template.currentData() 的 Meteor 文档及其在 helper 中的用法中有所暗示。

我需要对反应变量进行的工作不在视图范围内,因此不应在 Template.helper 中使用,而应在 template.autorun 中使用。

【讨论】:

    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 2015-12-17
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多