向模板实例变量传递调用方法调用的结果时出现异常

Exception in delivering result of invoking method call to template instance variable

本文关键字:调用 结果 异常 方法 实例 变量      更新时间:2023-09-26

我在服务器端创建了一个templateTitle方法来发布Mongo 中的一些数据

Theme = new Mongo.Collection("theme");
if (Meteor.isServer) {
    Meteor.startup(function () {
        Theme.insert({template: 'booking', value: 'val_example'});
    });
    Meteor.methods({
        templateTitle: function () {
            return Theme.findOne({template: 'booking'}, {value:1});
        }
    });  
}

在客户端,我试图通过调用templateTitle方法"订阅"该数据——在回调函数中,我想保存检索到的值并将其保存在反应变量中,但我在这里遇到了类型错误。

传递调用"templateTitle"的结果时出现异常:类型错误:无法读取空的属性"title"

if (Meteor.isClient) {
    Template.booking.created = function() {
        this.title = new ReactiveVar('');
    }
    Template.booking.helpers({
        templateTitle: function(){
            Meteor.call('templateTitle', function(err, data) {
                console.log(data); //data is okey
                Template.instance().title.set(data.value); //error on title
            });
            return Template.instance().title.get();
        }
    });
}

我也尝试过这种方式,但效果不如

if (Meteor.isClient) {
    Template.booking.created = function() {
        this.title = new ReactiveVar('');
        this.autorun(function () {
            Meteor.call('templateTitle', function(err, data) {
                this.title.set(data.value);
            });
        });
    }

"title"变量或回调函数通常有什么问题?

来自Template.instance()的Meteor文档:

与当前模板帮助程序、事件处理程序、回调或自动运行相对应的模板实例。如果没有,则为null。

我认为在这种情况下,您返回的是当前回调的模板实例(没有,因此为null),而不是当前helper。您应该能够绕过这一点,方法是在调用方法之前将模板实例保存在本地,然后在回调中引用它:

if (Meteor.isClient) {
  Template.booking.created = function() {
      this.title = new ReactiveVar('');
  }
  Template.booking.helpers({
      templateTitle: function(){
          var tmplInst = Template.instance();
          Meteor.call('templateTitle', function(err, data) {
              console.log(data); //data is okey
              tmplInst.title.set(data.value); //error on title
          });
          return Template.instance().title.get();
      }
  });
}