【问题标题】:Meteor - button click not updating value流星 - 按钮单击不更新值
【发布时间】:2016-11-24 08:31:56
【问题描述】:

我正在尝试在集合中获取一个随机文档并将其显示在页面上。每次加载页面都会成功,但我也想要一个按钮来完成这项工作。

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);
  }
});

加载页面或单击按钮时没有错误消息。

感谢任何帮助。 顺便说一句,“this.question.set('object', random);”里面的对象是什么。也许这就是我的问题所在。

【问题讨论】:

    标签: node.js mongodb templates meteor


    【解决方案1】:

    您可以大大简化您的代码并通过在您的帮助程序中选择一个随机对象来解决您的问题 - 即使您不希望它运行多次,它也会运行很多次。此外,由于您只查看单个对象,请使用 {{#with }} 而不是 {{#each }} - 这将避免数组转换步骤。

    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();
      }
    });
    

    【讨论】:

    • 谢谢米歇尔!那成功了。会话不是人们现在试图避免的吗?我听说 ReactiveDict 更好一些。但我也在某处读到它,会话包含在 ReactiveDict 中大声笑
    • Session IMO 本身并没有错。你可以使用一个反应变量来代替它。
    猜你喜欢
    • 2014-02-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2014-05-02
    相关资源
    最近更新 更多