为什么我的流星模板上下文数据没有被保存

Why is my Meteor template context data not being saved?

本文关键字:保存 数据 上下文 我的 流星 为什么      更新时间:2023-09-26

我对此感到挠头,因为我记得这段代码在过去的某个时候是工作的。当创建和渲染test时,我设置了this.data的值,但我无法在事件或帮助程序中检索它。我开始认为是一个包裹或什么东西把我的流星搞砸了。

<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不同。你不能把东西放进onCreatedthis.data,并期望能够在你的空格模板中使用它。铁路由器只是为了方便而把它储存在那里。

关于你的事件…好了,应该可以了。你所写的应该显示你的wheels。也许你是改变你的实例的data在某种程度上事先?当然,您可以使用Template.instance()来代替tmpl