【问题标题】:Exception in delivering result of invoking method call to template instance variable将调用方法调用的结果传递给模板实例变量时出现异常
【发布时间】:2015-03-19 21:52:54
【问题描述】:

我在服务器端创建了一个 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'的结果传递异常:TypeError: 无法读取 null 的属性“标题”

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' 变量或回调函数一般有什么问题?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    来自Meteor Docs for Template.instance()

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

    我认为在这种情况下发生的事情是您正在返回当前 callback 的模板实例(没有,所以 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();
          }
      });
    }
    

    【讨论】:

    • @ziomyslaw 您是否也包括了上述尝试中的Template.booking.created 部分?您需要在创建时将其作为模板实例的一部分启动;我只是想将这一行添加到您的助手中。我已经编辑了答案,所以希望它更清楚,并且有效
    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多