首页 > web前端 > js教程 > 正文

您可以直接从模板助手调用 Meteor 方法吗?

Linda Hamilton
发布: 2024-10-28 10:02:29
原创
306 人浏览过

 Can You Call Meteor Methods Directly from Template Helpers?

在模板助手中使用 Meteor 方法

在 Meteor 中,模板助手向模板提供反应数据。出现一个常见问题:我们可以直接从这些助手中访问 Meteor 方法吗?

考虑以下代码:

<code class="javascrip">// server-side method
Meteor.methods({
  // viewTest method to return a string
  viewTest: function(str) {
    return str;
  }
});

// client-side helper
Template.helloWorld.helpers({
  // attempt to call 'viewTest' method
  txt: function() {
    return Meteor.call('viewTest', 'Hello World.');
  }
});</code>
登录后复制

当尝试渲染模板时,助手函数会抛出错误,表明该方法不存在。这是因为 Meteor 会在客户端注册方法之前尝试渲染模板。

替代实现

Meteor 0.9.3.1 中有一个更新的方法可以解决这个问题问题:

<code class="javascript">// client-side template
Template.helloWorld.helpers({
  txt: function() {
    return Template.instance().myAsyncValue.get();
  }
});

// client-side 'created' callback
Template.helloWorld.created = function() {
  // create a ReactiveVar instance and attach it to the template
  this.myAsyncValue = new ReactiveVar("Waiting for response from server...");
  
  // call the 'getAsyncValue' method and update the ReactiveVar when the callback fires
  Meteor.call('getAsyncValue', (err, asyncValue) => {
    if (err) console.log(err);
    else this.myAsyncValue.set(asyncValue);
  });
};</code>
登录后复制

此解决方案使用 ReactiveVars,它们是与模板实例绑定的反应式数据源。通过将方法结果存储在 ReactiveVar 中并在回调中更新它,助手可以响应式地访问返回值。

以上是您可以直接从模板助手调用 Meteor 方法吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!