简体   繁体   中英

typeahead.js: change data source, which is given as a helper

I need to change the helper source of my typeahead-input-field ( sergeyt:typeahead ):

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

Now I want to change it on any event like this:

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'
        }
    }
})

helpers

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'];
    }
});

As I would change the dataset like this...

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

... I couldn't use the helper. So I don't know how to get back to origin

Perhaps you could use a reactive variable for this?

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

events

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

helpers

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');
  });
});

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