سؤال

I'm completely new to Meteor, and I was doing the leaderboard example. I have a little problem with my code.

I was trying to add a toggle button to toggle sorting. The toggling and all is working fine, but the button's text doesn't update.

My javascript code:

if (Meteor.isClient) {
    Meteor.startup(function () {
        Session.set("sortMethod", "score");
    });

    ...

    Template.leaderboard.players = function () {
        if (Session.equals("sortMethod", "name"))
            return Players.find({}, {sort: {name: 1}});
        else if(Session.equals("sortMethod", "score"))
            return Players.find({}, {sort: {score: 1}});
    };

    ...

    Template.leaderboard.sortMethod = function () {
        return Session.get("sortMethod");
    }

    ...

    Template.leaderboard.events({
    'click input.sortToggle': function () {
      Session.equals("sortMethod", "name") ? Session.set("sortMethod", "score") : Session.set("sortMethod", "name");
    }
  });
}

My handlebars template:

<template name="leaderboard">
  <!-- this is where it goes wrong, the button text doesn't update at {{sortMethod}} -->
  <input type="button" class="sortToggle" value="sort by {{sortMethod}}">
  <!--  -->
  <div class="leaderboard">
    {{#each players}}
      {{> player}}
    {{/each}}
  </div>

  {{#if selected_name}}
  <div class="details">
    <div class="name">{{selected_name}}</div>
    <input type="button" class="inc" value="Give some points" />
  </div>
  {{else}}
  <div class="none">Click a player to select</div>
  {{/if}}
</template>

Note: I removed some irrelevant code.

هل كانت مفيدة؟

المحلول

It works if you use a button instead:

<button class="sortToggle">sort by {{sortMethod}}</button>

With the corresponding change to events:

'click .sortToggle': function () { ...

Changing the value of an input was reported as an issue in the past, but it was closed. Perhaps it needs to be reopened.

نصائح أخرى

I am not sure if this is a bug or a feature. I think the problem stems from trying to update an input element that has focus. So the fix is to blur() the element on the end of your event handler. Like this:

'click input.sortToggle': function ( event ) {
    Session.equals("sortMethod", "name") 
      ? Session.set("sortMethod", "score") 
      : Session.set("sortMethod", "name");
    $( event.currentTarget ).blur();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top