首頁 > 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學習者快速成長!