admin管理员组

文章数量:1406943

I have a searchbox on which I initialize typeahead when I click on it, to some data from the server. Depending on the current page, I need to show/hide a footer in the search dropdown.

I went for the approach to destroy the typeahead and then recreate it, according to my needs. In this way, I also refresh the data from server, in case there's something changed.

For destroy I use this this.$("#searchQuery").typeahead('destroy'); right at the top of the function that needs to initialize the typeahead, but the problem is that the menu is not destroyed. If I look at the dom, there are 4-5 or even more typeahead menu created.

So my question is, how can I properly 'reinitialize' a typeahead menu?

I forgot to mention I am using twitter typeahead

I have a searchbox on which I initialize typeahead when I click on it, to some data from the server. Depending on the current page, I need to show/hide a footer in the search dropdown.

I went for the approach to destroy the typeahead and then recreate it, according to my needs. In this way, I also refresh the data from server, in case there's something changed.

For destroy I use this this.$("#searchQuery").typeahead('destroy'); right at the top of the function that needs to initialize the typeahead, but the problem is that the menu is not destroyed. If I look at the dom, there are 4-5 or even more typeahead menu created.

So my question is, how can I properly 'reinitialize' a typeahead menu?

I forgot to mention I am using twitter typeahead

Share Improve this question asked Sep 19, 2013 at 6:28 Cristian HoldunuCristian Holdunu 1,9282 gold badges18 silver badges43 bronze badges 2
  • What is the jquery plugin that you are using? – Krasimir Commented Sep 19, 2013 at 6:31
  • You don't need to reference jQuery via Window using this.$(...) you can just do $("#searchQuery").typeahead("destroy"); and that could cause you problems depending on the function that you said you are using, which that line is in... because this may no longer represent the Window see developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Pricey Commented Sep 29, 2013 at 23:29
Add a ment  | 

1 Answer 1

Reset to default 5

You don't need to reference jQuery via this like you showed here

this.$("#searchQuery")

You should just do

$("#searchQuery").typeahead("destroy");

Without seeing more of an example I would say your problem might be because this inside your function is being bound to a different object than the one you were expecting.

See: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/this

Your line is inside your function so you can not guarantee that this will be Window and you have no need to use it in this case.

If this is not the problem then please provide a full html and javascript example, preferably on JsFiddle.

本文标签: javascriptDestroy typeahead after the menu has been closedStack Overflow