yuku / textcomplete

Autocomplete for HTMLTextAreaElement and more.
https://yuku.takahashi.coffee/textcomplete/
MIT License
1.74k stars 303 forks source link

Problem to show suggestions based on condition #270

Closed shivrajsa closed 8 years ago

shivrajsa commented 8 years ago

Based on some condition I want to display different suggestions, please refer below code, where if condition is 0 I want to use obj1 else if it is 1 then I want to use obj2.

But below code is not working as expected, every time I get suggestions from only one object which was selected first time as per condition. Please help to solve the problem

function autoComplete(condition) {
  var obj1 = {
      A: 'a',
      B: 'b'
    },
    obj2 = {
      A: 'X',
      B: 'Y'
    },
    words = ['A', 'B'];

  $('.handsontableInput').textcomplete([{
      match: /(^|\b)(\w{0,})$/,
      search: function(term, callback) {
        callback($.map(words, function(word) {
          return word.indexOf(term) === 0 ? word : null;
        }));
      },
      template: function(word) {
        var x;
        if (condition == 0)
          x = word + '&nbsp&nbsp' + '<span class="NotationsAutoComplete">' + obj1[word] + '</span>';
        else if (condition == 1)
          x = word + '&nbsp&nbsp' + '<span class="NotationsAutoComplete">' + obj2[word] + '</span>';
        return x;
      },
      replace: function(word) {
        return word + ' ';
      }
    }
yuku commented 8 years ago

I get suggestions from only one object which was selected first time as per condition

It is because the condition argument is in closure. In other words, the condition is fixed when you execute the autoComplete function and never change.

You can fix the problem by moving the condition from function argument to outer variable.

var condition;

function autoComplete() {
  ...
  $('..').textcomplete([{
    template: function (word) {
      if (condition) {
        return word + '...';
      } else {
        ...
      }
    }
  }])
}
shivrajsa commented 8 years ago

Thank you, its working now :-)