Meteor – Stop Tracker Autorun when Template is Destroyed (user leaves page)
在我的 Meteor 模板中,我有一个名为 ohlcInit() 的函数,它会在 Mongo 中有新数据时自动运行:
1
2 3 4 5 6 7 8 9 10 |
Template.Live.rendered = function(){
function ohlcInit() { Tracker.autorun(function() { |
当用户在定义了这一切的页面/模板上时,这很有效,但是一旦用户导航到站点上的另一个 URL 并且模板被破坏,控制台中就会抛出错误:
Exception from Tracker recompute function: undefined is not a function
TypeError: undefined is not a function
at ohlcInit (http://localhost:3000/client/views/live/live.js?dd5fb618daf9ea9e233c37caaaa9ed200fe3e987:271:33)
at http://localhost:3000/client/views/live/live.js?dd5fb618daf9ea9e233c37caaaa9ed200fe3e987:306:5
at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:288:36)
at Tracker.Computation._recompute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:302:14)
at Tracker.flush (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:430:14)
当用户导航到新的 URL/模板时,您如何安全地停止/结束自动运行计算?
我正在使用 iron:router.
使用新的 Template.autorun 函数,它会在模板被销毁后自动清理。要在 rendered 回调中使用它,只需将 Tracker.autorun 替换为 this.autorun.
- 谢谢!刚刚在 Meteor github repo 中看到了同样的解释:github.com/meteor/meteor/issues/2057
- 我遇到了同样的上述问题,但我在客户端上的 Meteor 方法的回调中开始了我的 Tracker.autorun 调用。我正在服务器上启动一个进程,然后如果启动进程没有错误,则需要监听一些数据库值。它们工作正常,除非我在销毁模板时遇到上述相同的错误。使用 this.autorun 在回调范围内不起作用。我认为由于范围问题,无法在 .destroyed 中调用 stop 。
- 我想到了。只需要在我的 Meteor 方法调用之前在正确的范围内设置一个 var template = Template.instance() 。然后在回调代码中调用 template.autorun(function … 引用上述变量即可完美运行。
- 你好@DavidWeldon,你能举个简单的例子吗??我已经阅读了文档,但不明白,,
- @KarinaL 看看我对这里和这里的回答。希望这些会有所帮助。如果您有一些无法使用的特定代码,我建议您提出一个新问题。
来源:https://www.codenong.com/26925096/