【问题标题】:Meteor with Typeahead: where to call typeahead() on input element?带有 Typeahead 的 Meteor:在哪里调用输入元素的 typeahead()?
【发布时间】:2015-12-21 14:59:39
【问题描述】:

我正在使用带有 Iron Router 的 Meteor,但似乎无法提前输入(此版本:https://github.com/bassjobsen/Bootstrap-3-Typeahead)。

这里有一些代码:

HomeController = RouteController.extend({
  //....
  after: function () {
    var tags = this.getData().tags;
    console.log(tags);
    if(tags.length > 0) {
      var tags = ['hello', 'world'];
      console.log("Adding typeahead for tags to ", $('.input-search')[0]);
      console.log("tags: ", tags);
      $('.input-search').typeahead({
        source: tags,
        updater: function(item) {
          Router.go('/projects/tag/' + item);
        }
      });
    }
  },

我有一个作为应用程序布局一部分的标题,并且有这样的输入:

<input type="text" class="form-control input-search" data-provide="typeahead" placeholder="Search">

after: 函数中的 jQuery 正确获取输入。但是在输入上调用 typeahead 似乎并没有正确激活 typeahead:在输入中输入时,什么也没有发生。

但是,如果我将 typeahead 调用包装在 setTimeout 中,它确实有效。

当然,每当你开始在 setTimeouts 中包装东西时,就会出现一些问题。

使用 Iron Router 时,在哪里/何时是初始化 typeahead 的正确位置?

【问题讨论】:

    标签: meteor bootstrap-typeahead iron-router


    【解决方案1】:

    您可以在模板的rendered 函数中初始化预输入。例如:

    Template.mytemplate.rendered = function() {
          $('.input-search').typeahead({
            source: tags,
            updater: function(item) {
              Router.go('/projects/tag/' + item);
            }
          });
    };
    

    【讨论】:

    • 我也试过了,但遇到了同样的问题:它只在包裹在 setTimeout 中时才有效。
    【解决方案2】:

    我想通了。

    您需要确保插件使用的任何输入都被 Meteor “保留”,即不重新渲染。最简单的方法是确保输入具有 ID 属性。因此,将我的搜索输入更改为此修复了它:

    <input type="text" id="input-search" class="form-control" data-provide="typeahead" placeholder="Search">
    

    相关文档:http://docs.meteor.com/#template_preserve

    【讨论】:

      【解决方案3】:

      从 Meteor 1.0.3.1 和 iron:router@1.0.7 开始,工作解决方案是安装 sergeyt:typeahead 并像这样预先输入:

      Template.MyTemplate.rendered = function () {
          Meteor.typeahead.inject();
      }
      

      顶级模板只能初始化一次。

      【讨论】:

        【解决方案4】:

        我写了一篇关于这个的文章,你可以阅读它here

        总之,您使用 javascript 来选择和更改元素的实现在反应式环境中是不好的做法。我已经尝试过这种方式,但这是一个巨大的痛苦。

        我发现你可以创建一个帮助器,它返回你的 typeahead 数据的 JSON 字符串并使用 data-source 属性,就像这样

        JS

        Template.myHelper.helper({
          typeahead : function(){
            return JSON.stringify(Session.get("typeahead"));
          }
        });
        

        HTML

        <template name="myTemplate">
            <input data-source="{{typeahead}}" data-provide="typeahead" id="blah" type="text" />
        </template>
        

        【讨论】:

          猜你喜欢
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-11
          • 1970-01-01
          • 1970-01-01
          • 2013-07-28
          相关资源
          最近更新 更多