简体   繁体   中英

Meteor helpers not acting as expected

HTML

<input class="esInput"></input>

<ul class="search-bottom {{toggleSearchBottom}}>
   <li>sthsth</li>
   <li>sthsth</li>
   and so on
</ul>

JS

Template.search.helpers({
    toggleSearchBottom: function(){
        if($('.esInput').val().length == 0){
            return '';
        } 
        if($('.esInput').val().length >= 1){
            return 'hidden-tn hidden-xxs hidden-xs';
        }
    }
})

This is my code. When I type something in the .esInput the second if statement will not be activated. Amd I doing something wrong? When I console.log the .val.length() , I get the correct number. (0 when nothing, 1 or more when typed).

I'm trying to hide the element wwhen input has value.

I'm not an expert on meteor but I think I know what went wrong here. You will notice that function toggleSearchBottom is called only once. When the page loads it will trigger once, the class will be assigned and that's it.

Meteor has no way of knowing that you want to trigger this function each time esInput field's value has changed. This might be slightly confusing because Meteor is so smart when working with sessions and collections, but those automatic bindings do not work for arbitrary DOM.

You will have to take a bit different approach, I created a MeteorPad with an example. But this is the core of solution:

Template.body.events({
    "keyup .esInput": function(event) {
      if($(event.target).val().length > 0) {
        $("#state").addClass("hide");
      } else
      {
        $("#state").removeClass("hide");
      }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM