javascript - 为什么我的 Meteor 模板上下文数据没有被保存?

标签 javascript meteor

我对此感到摸不着头脑,因为我记得这段确切的代码在过去的某个时刻工作过。创建并呈现 test 时,我设置了 this.data 的值,但无法在事件或帮助程序中检索它。我开始认为某个包裹或其他东西搞砸了我的 Meteor。

<template name="test">
  <button>click me</button>    
</template>
Template.test.onCreated(function(){
  // here I am setting the data context of the test template
  this.data = {
    doors: 5
  };

  // when I hover over `this` in Chrome is indeed shows the object
  debugger
});

Template.test.onRendered(function(){

  this.data = {
    wheels: 4
  };
  // when I hover over `this` it also shows the object
  debugger

  var changeDataContext = function(obj){
    this.data = obj;
  };

  changeDataContext( {engine: 1} );

  // when I hover over `this` it shows the old value of `this`, not the new one with {engine: 1}
  this;
  debugger
});


Template.test.events({

  'click button': function(e, tmpl){
    tmpl;

    // when I hover over `tmpl` it shows null for `data`???
    debugger
  }

});

Template.test.helpers({

  images: function () {
    this;

    // when I hover over `this` it shows null for the value of `this`???
    debugger
    return this.wheels;
  }

});

编辑

这是一个 MeteorPad 概述了问题:

http://meteorpad.com/pad/Cqw3fWieJfspK2eYv/Leaderboard

在此处查看调试器语句:

http://app-5p5urzku.meteorpad.com/

最佳答案

这是您的范围的问题。首先,对于 onRendered,您不能在函数内使用 this 并期望它在更高的范围内被视为像 this:

Template.test.onRendered(function(){

  this.data = {
    wheels: 4
  };

  var self = this; // we save this scope's `this` for later

  var changeDataContext = function(obj){
    this.data = obj; // here, `this` refers to the current scope, ergo your changeDataContext function! onRendered's `this` does not get altered.
    self.data = obj; // here, we refer to the `self` variable that you set earlier. It should work.
  };

  changeDataContext( {engine: 1} );

  // tadaaaaaaaaaa
  this;
  debugger
});

然后,对于帮助者:this 代表数据上下文,而不是模板实例。如果您想要模板实例,请使用 Template.instance():

Template.test.helpers({

  images: function () {
    var tmpl = Template.instance();
    if (tmpl.data)
       return tmpl.data.wheels;
  }

});

请注意:数据上下文与Template.instance().data不同。您不能将内容放入 onCreated 中的 this.data 中,并期望能够在空格键模板中使用它。为了方便起见,铁路由器也将其存放在那里。

至于你的事件...好吧,它应该有效。您所写的内容应该向您展示轮子。也许您事先以某种方式更改了实例的数据?可以肯定的是,您可以使用 Template.instance() 而不是 tmpl

关于javascript - 为什么我的 Meteor 模板上下文数据没有被保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066438/

相关文章:

JavaScript PreventDefault 不起作用,也不返回 false;

meteor - 如何避免cursor.observe 上的竞争条件?

javascript - 搜索栏不会随着 div 高度动画消失

java - 是否有可用于 Java、C++ 和 JS 的可下载的 eclipse 包

javascript - 使用 Meteor 和 Iron Router 创建用户配置文件页面

javascript - 在 Meteor 中插入抓取的内容(通过 Cheerio)时出现问题

JavaScript 函数返回 'NaN' 或 'undefined'

javascript - 通过 Twilio npm 包发送短信 - 错误找不到 - 错误 : Cannot find module './webhooks'

javascript - 如何从循环中获取匹配项的总和?

javascript - 测量由 Javascript 发起的更改渲染时间