Я новичок в Meteor и хочу создать слайд-шоу с элементами из коллекции, в данном случае простыми словами. Слайд-шоу должно управляться кнопками «назад» и «вперед» и заменять текущее слово.
В JavaScript/jQuery я бы создал массив объектов и контрольный индекс с ограничениями через операторы if, поэтому индекс никогда не может упасть ниже нуля или выйти за пределы длины массива.
См. скрипку для рабочего примера:
http://jsfiddle.net/j0pqd26w/8/
$(document).ready(function() {
var wordArray = ["hello", "yes", "no", "maybe"];
var arrayIndex = 0;
$('#word').html(wordArray[arrayIndex]);
$("#previous").click(function(){
if (arrayIndex > 0) {
arrayIndex -= 1;
}
$('#word').html(wordArray[arrayIndex]);
});
$("#next").click(function(){
if (arrayIndex < wordArray.length) {
arrayIndex += 1;
}
$('#word').html(wordArray[arrayIndex]);
});
});
Метеор
Мне любопытно, как реализовать это в отношении наилучшей практики в метеоре и придерживаться реактивного шаблона, поскольку я все еще пытаюсь обдумать эту интересную структуру. Мое первое препятствие - перевести
if (arrayIndex < wordArray.length)
// to
if (Session.get("wordIndex") < ( (((length of collection))) )
Согласно документам, я должен выполнить поиск в коллекции, но позже мне удалось вернуть пустой массив только с помощью выборки. Извините, если это затянулось, но любой вклад будет оценен, чтобы помочь мне понять это.
collection.find([selector], [options])
cursor.fetch()
Это код, который у меня есть до сих пор:
Words = new Mongo.Collection("words");
if (Meteor.isClient) {
// word index starts at 0
Session.setDefault("wordIndex", 0);
Template.body.helpers({
words: function () {
return Words.find({});
},
wordIndex: function () {
return Session.get("wordIndex");
}
});
Template.body.events({
"submit .new-word": function (event) {
// This function is called when the word form is submitted
var text = event.target.text.value;
Words.insert({
text: text,
createdAt: new Date() //current time
});
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
},
'click #previous': function () {
// decrement the word index when button is clicked
if (Session.get("wordIndex") > 0) {
Session.set("wordIndex", Session.get("wordIndex") - 1);
}
},
'click #next': function () {
// increment the word index when button is clicked
if (Session.get("wordIndex") < 10 ) {
Session.set("wordIndex", Session.get("wordIndex") + 1);
}
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
});
}