gpt4 book ai didi

javascript - meteor .js : Reusing methods and functions in events and helpers

转载 作者:行者123 更新时间:2023-11-30 16:53:50 27 4
gpt4 key购买 nike

我是 Meteor.js 的新手,非常感谢任何人在以下两个问题上提供的帮助。我正在制作一个抽认卡应用程序,您可以在其中单击箭头以显示下一张抽认卡。抽认卡已预先洗牌,您可以通过单击箭头浏览整个卡片组。

Router.route ( '/', function () {
Session.set ('wordArray', _.shuffle( Words.find().fetch() ) );
Session.set ( 'index', 0 )
this.render('wordPage');
})

我的wordPage模板如下:

<template name="wordPage">
<div class="post">
<div id = "arrow-right" ></div>
{{ > wordItem word index }}
</div>
</template>

我的wordPage.js如下:

Template.wordPage.helpers ({
word: function ( index ) {
return Session.get ( 'wordArray' ) [ index ] ;
},

index: function () { return Session.get ( 'index' ); },
})

wordPage通过上面的方法将word和index传递给更详细的tempalte。

Template.wordPage.events ( { 
"click #arrow-right": function ( e ) {
if ( Session.get ('index') < Session.get ('wordArray').length-1 ) {
console.log(Session.get('index'));
Session.set ( 'index', Session.get ( 'index' ) + 1);
}
}
} )

我的两个问题:

1) 我想在每次加载页面时打乱抽认卡,我能弄清楚如何轻松做到这一点的唯一方法(即不打乱整个 MongoDB 数据库)是将整个抽认卡保存在一个通过 Sessions 变量的数组。如何在我不使用 Sessions 变量的情况下实现某些东西?每次进入根目录或在某处单击洗牌按钮时洗牌的最佳方式是什么?

2) 我在 wordPage.js 文件中大量使用 Session.get/Session.set。有什么方法可以保存这些函数以便在 wordPage 帮助器和事件中都可以访问吗?我试着做这样的事情:

var word = function ( index ) { return Session.get ( 'wordArray' ) [index]; }

在 helpers 和 events block 之外,然后只是尝试使用 word(index)。但它似乎只有在我将 word 设为全局变量时才有效。

提前致谢。

最佳答案

当你遇到关于范围的严重问题时(我在哪里定义它,我如何使用它,好吧,现在我的代码到处都是 Session 我不知道我是如何操作的我的数据,当我尝试重构某些东西时我想烧掉我的电脑)你有一个简单的解决方案:
package .

一个包可以让你清楚地定义你的数据,并在你需要的地方小心地导入它。您可以定义无痛的唯一访问器(而不是到处都是 Session 的东西)。您可以一劳永逸地定义您的数据是什么,如何访问、更改、删​​除、打乱……


这是您的用例的样板文件。

meteor create --package cards

删除测试。在 package.js 中,移除 onTest 回调,您暂时不需要它。您将需要 underscoremongo,因此将它们添加到 onUse 回调中:

api.use('underscore');
api.use('mongo');

现在在您的 cards.js 新文件中:

Words = new Meteor.Collection('words'); //Notice the absence of var*
WordsAccessor = {
get shuffledWords() {
return _.shuffle( Words.find().fetch() );
},
wordFromIndex : function(index) {
return Words.find().fetch()[index];
},
addWords : function(words) {
words.forEach(function(word) {
Words.insert(word);
});
}
};

最后,export访问器(accessor):

api.export('WordsAccessor');

有了这种模式,你几乎可以做任何你想做的事。您可以创建一个单词数组以避免一直碰到 minimongo,在第一次使用时填充 Words 集合,...


*No var 语句意味着该变量是包作用域的并且可以导出,然后使用 meteor add 全局导入或使用 api.use 在另一个包范围内导入.

关于javascript - meteor .js : Reusing methods and functions in events and helpers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090294/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com