首頁  >  文章  >  web前端  >  您可以直接從模板助手呼叫 Meteor 方法嗎?

您可以直接從模板助手呼叫 Meteor 方法嗎?

Linda Hamilton
Linda Hamilton原創
2024-10-28 10:02:29308瀏覽

 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn