简体   繁体   English

流星助手的作用与预期不同

[英]Meteor helpers not acting as expected

HTML 的HTML

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

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

JS 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. 当我在.esInput键入.esInput ,第二个if语句将不会被激活。 Amd I doing something wrong? 我做错了吗? When I console.log the .val.length() , I get the correct number. 当我console.log .val.length() ,我得到了正确的数字。 (0 when nothing, 1 or more when typed). (无则为0,键入时为1或更多)。

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. 您会注意到,功能toggleSearchBottom仅被调用一次。 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. 每次esInput字段的值更改时,Meteor都不知道要触发此功能。 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. 这可能有点令人困惑,因为Meteor在处理会话和集合时非常聪明,但是这些自动绑定不适用于任意DOM。

You will have to take a bit different approach, I created a MeteorPad with an example. 您将不得不采取一些不同的方法,我创建了一个带有示例的MeteorPad 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");
      }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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