gpt4 book ai didi

javascript - 模板实例变量调用方法调用结果传递异常

转载 作者:可可西里 更新时间:2023-11-01 10:03:52 26 4
gpt4 key购买 nike

我在服务器端创建了一个 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 方法“订阅”该数据 - 在回调函数中,我想保存检索到的值并将其保存在 react 变量中,但我在这里遇到类型错误。

Exception in delivering result of invoking 'templateTitle': TypeError: Cannot read property 'title' of 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”变量或回调函数一般有什么问题?

最佳答案

来自Meteor Docs for Template.instance() :

The template instance corresponding to the current template helper, event handler, callback, or autorun. If there isn't one, 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();
}
});
}

关于javascript - 模板实例变量调用方法调用结果传递异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29155681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com