清理我的流星函数和查询

Cleaning up my Meteor functions and queries

本文关键字:查询 函数 流星 我的      更新时间:2023-09-26

我有许多客户端函数,包括find()查询和日期/时间翻译,我已经在我的项目中的多个地方列出了这些函数。对于 Meteor,放置这些内容的最佳位置在哪里,以便我可以消除冗余和可能的不一致?

另外,我将如何引用,例如,find() 查询?会是这样吗?或者有没有更好的方法来做到这一点?

// JS file calling my re-usable function
Template.templatename.events({
  'click .class': function {
    var cats = function spaghetti();
    return cats;
  }
});
// JS file with re-usable functions
function spaghetti() {
  return Collection.find();
}
是否确实

要在单击事件中返回集合?

如果您指的是帮助程序而不是事件,则可以执行以下操作:

/**
 * Only on catsList template
 */
Template.catsList.helpers({
  cats: function() {
    return Cats.find();
  }
})
/**
 * On all templates
 */
Template.registerHelper('cats', function() {
  return Cats.find();
});

我认为这就是您要找的,例如,如果您在 7 个不同的模板上有相同的Collection.find();(例如),您可以从 meteor-templates-extension 使用此功能。

.HTML

<body>
  {{> foo}}
  {{> foo2}}
</body>
<template name="foo">
  {{bar}}
  <button type="button">Click</button>
</template>
<template name="foo2">
  {{bar}} 2
  <button type="button">Click 2</button>
</template>
<!-- and so on -->

.JS

Template.foo.helpers = function () {
 thisHelperIsAvaibleEverywhere:function(){
     return "Test";
  }
};
Template.foo.events({
  'click button': function (event, template) {
    console.log("foo button clicked");
  }
});
Template.foo2.inheritsHelpersFrom("thisHelperIsAvaibleEverywhere");
Template.foo2.inheritsEventsFrom("foo");

因此,现在两个模板Foo and Foo2可以使用相同的帮助程序,并且它们将使用名为 foo 的相同事件

看看并告诉我是否有效