簡體   English   中英

Meteor,如何從另一個助手訪問助手?

[英]Meteor, how to access to a helper from another helper?

我有一個好幫手

Template.user_profile.helpers({
  user:function() {
     return Meteor.users.find({'profile.front_name':Session.get('slug')}).fetch()[0];
  }
});

我想在集合中添加一個幫助程序,它可以訪問user幫助程序並將其_id與當前用戶_id進行比較,以判斷用戶是否正在訪問自己的配置文件。 我正在使用一些非常難看的東西:

Template.user_profile._tmpl_data.helpers.user()

最終代碼:

Template.user_profile.helpers({
  user:function() {
     return Meteor.users.find({'profile.front_name':Session.get('userId')}).fetch()[0];
  },
  isCurrentUser: function() {
    return Template.user_profile._tmpl_data.helpers.user()._id === Meteor.userId();
  }
});

有沒有更好的方法來訪問另一個幫手?

我剛剛在控制台中意外地發現了這個:

Template.registerHelper
function (name, func) {                                                                             
  Blaze._globalHelpers[name] = func;                                                                                   
} 

所以, Blaze._globalHelpers是我們正在尋找的!

您可以使用以下命令調用模板幫助程序(不是全局幫助程序 - 這是outluch的答案)

Template.tplName.__helpers.get('helper').call()

MDG建議使用常規函數,然后將其傳遞給幫助程序,事件等。 看到這里

更新16.06.16
實際上我強烈建議簡單地使用manuel:viewmodel - 它減輕了很多Blaze的頭痛......

當我在尋找一種從另一個助手調用幫助器的方法時,我發現Meteor 1.0定義了“Template.registeredHelpers”,可供所有其他助手使用。 https://docs.meteor.com/#/full/template_registerhelper

Template.registerHelper("checkedIf",function(value){
  return value?"checked":"";
});

您可能甚至不需要像這樣調用幫助器。 已經內置了currentUser助手。

http://docs.meteor.com/#template_currentuser

{{currentUser}}

也許這對你有用:

  //js
Template.foo.helpers({ bar: function() {
 return this.userId == Meteor.userId(); },
 domain: function() {
 var a = document.createElement('a'); a.href = this.url;
 return a.hostname;
 } });

 ownsDocument = function(userId, doc) { return doc && doc.userId === userId;}

 Posts = new Meteor.Collection('posts');
 Posts.allow({
 update: ownsDocument, remove: ownsDocument
 });

  //html
{{#if bar}}<a href="{{pathFor 'postEdit'}}">Edit</a>{{/if}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM