Silvio Li Silvio Li - 4 months ago 14
Node.js Question

Meteor - button click not updating value

I am trying to get a random document in the collection and display it on the page. It is successful every time I load the page, but I want a button to do the work as well.

main.html

<head>
<title>test</title>
</head>

<body>
<h1>Random Question</h1>
{{> question}}
</body>

<template name="question">
<button>Click Me</button>
{{#each object}}
{{question}}
{{a}}
{{b}}
{{c}}
{{d}}
{{answer}}
{{points}}
{{/each}}

</template>


main.js

import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';

import './main.html';
Resolutions = new Mongo.Collection('quiz');

Template.question.created = function () {

var random = get_random();

this.question = new ReactiveDict();
this.question.set('object', random);
};

function get_random(){
var collection_size = Resolutions.find().count();
var random = Math.floor(Random.fraction() * collection_size);
// choose a random item by skipping N items
var item = Resolutions.findOne({},{
skip: random
});
var objArray = $.makeArray(item);
return objArray;
}

Template.question.helpers({
object: function () {
return get_random();
}
});

Template.question.events({
'click button': function (event, template) {
// increment the counter when button is clicked
var random = get_random();
template.question.set('object', random);
}
});


There is no error message when I load the page or click the button.

Any help is appreciated.
Btw, what is the object inside "this.question.set('object', random);". Maybe that's where my issue is.

Answer

You can considerably simplify your code and also solve your problem by not picking a random object in your helper - that will run many times, even when you don't expect it to. Also since you're only viewing a single object, use {{#with }} instead of {{#each }} - this will avoid the array conversion step.

html:

<template name="question">
  <button>Click Me</button>
  {{#with object}}
      {{question}}
      {{a}}
      {{b}}
      {{c}}
      {{d}}
      {{answer}}
      {{points}}
  {{/with}}
</template>

js:

import { Template } from 'meteor/templating';
import './main.html';

Resolutions = new Mongo.Collection('quiz');

Template.question.created = function () {
  setRandom(); // initialize the random selection
};

function setRandom(){
  var collection_size = Resolutions.find().count();
  var random = Math.floor(Random.fraction() * collection_size);
  Session.set('random',random);
}

Template.question.helpers({
  object: function () {
    return Resolutions.findOne({},{ skip: Session.get('random') });
  }
});

Template.question.events({
  'click button': function (event, template) {
    setRandom();
  }
});
Comments