Kwhitejr
Kwhitejr

Reputation: 2306

Meteor: Display random collection object on event

I am creating my first Meteor app. Simple idea: user can submit a pun (prompt and answer) on one template or view a random pun on another template. Puns are contained in the "Puns" collection. Insertions are working, but I cannot figure out how to display a random Puns object -- either (1) when the template is first rendered or (2) when user clicks the "more pun" button.

(1) Meteor - Client

Session.setDefault('randomPun', null);

Template.punDisplay.helpers({
  pun: function () {
    var array = Puns.find().fetch();
    var randomIndex = Math.floor( Math.random() * array.length );
    var pun = array[randomIndex];
    Session.set('randomPun', pun);
  }
});

Template.displayPun.events({
  // Should load a pun when "more pun" btn is clicked.
  'click [data-action="getPun"]': function (event, template) {
    Session.set('randomPun', pun);
  }
});

(2) Template

<template name="punDisplay">
  <div class="container">
    <h1 class="item">take a pun</h1>
      {{#with randomPun}}
        <p class="item">{{prompt}}</p>
        <p class="item">{{answer}}</p>
      {{/with}}
    <button class="item btn" data-action="getPun">more pun</button>
  </div>
</template>

Again, my desired outcome is that there will be a pre-loaded pun object (prompt and answer) when the user first arrives at the "displayPun" template and then react with a random pun object from Puns collection if the user clicks the "more pun" button.

Thank you and mahalo for any advice.

Upvotes: 1

Views: 108

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

Basically you need to initialize the random pun when the template is rendered and then update on click. The Random.choice() function is useful for grabbing a random member of an array.

function selectRandomPun(){
  var puns = Puns.find().fetch;
  Session.set('randomPun', Random.choice(puns));
}

Template.punDisplay.onCreated(selectRandomPun);

Template.punDisplay.helpers({
  randomPun: function () {
    return Session.get('randomPun');
  }
});

Template.displayPun.events({
  'click [data-action="getPun"]': selectRandomPun
});

Upvotes: 1

Related Questions