typeahead.js:更改数据源,作为帮助程序提供

时间:2015-12-15 15:11:10

标签: javascript meteor typeahead.js

我需要更改typeahead-input-field(sergeyt:typeahead)的帮助源:

<template name="searchMain">
    <input  class="typeahead" 
            type="text" 
            autocomplete="on" 
            spellcheck="off" 
            data-sets="searchData" />
</template>

现在我想在任何类似的事件上更改它:

Template.searchMain.events({
    'keyup .typeahead': function(event, template) {
        if ($(event.currentTarget).val() == 'change') {
            // the user typed 'change'
            // now change data source to 'newData'
        }
        else {
            // else use original data source 'searchData'
        }
    }
})

助手

Template.searchMain.helpers({
    searchData: function() {
        // build some dataset from collections
        return ['complex', 'old', 'dataset'];
    },
    newData: function() {
        // build some dataset from collections
        return ['another', 'new', 'dataset'];
    }
});

因为我会像这样更改数据集......

$('.typeahead').typeahead('destroy');
$('.typeahead').typeahead({
    local: data
});

......我无法使用帮手。所以我不知道如何回归原点

1 个答案:

答案 0 :(得分:0)

也许您可以使用reactive变量吗?

<template name="searchMain">
    <input  class="typeahead" 
            type="text" 
            autocomplete="on" 
            spellcheck="off" 
            data-sets="varDataSets" />
</template>

<强>事件

Template.searchMain.events({
    'keyup .typeahead': function(event, template) {
        if ($(event.currentTarget).val() == 'change') {
            Session.set('dataSets', 'new');
        }
        else {
            Session.set('dataSets', 'search');
        }
    }
})

<强>助手

Template.searchMain.helpers({
  varDataSets: function() {
    if (Session.get('dataSets') === 'search') {
      // build some dataset from collections
      return ['complex', 'old', 'dataset'];
    }
    // build some dataset from collections
    return ['another', 'new', 'dataset'];
  }
});

<强> onRendered

Template.searchMain.onRendered(function () {
  this.autorun(function () {
    // will trigger the autorun everytime dataSets changes
    Session.get('dataSets');
    Meteor.typeahead.inject('.typeahead');
  });
});