Question

I've written a plugin to highlight terms used to find a page. The source is also available.

My problem is, if you look at the first link's inline JavaScript, I've made a custom textPlacement function to handle the insertion of the display bar (it looks a bit like Stack Overflow's).

As you can see, I have an event handler on the button that is inserted. I have coded the removal of the bar, but I'd also like to remove the highlighting of the terms. The plugin has a method for doing this called toggleTermHighlighting().

How can I call that method from inside the anonymous function on the example page? Would I need to make it this.toggleTermHighlighting = function() {}. I've tried passing in an instance of this to the first argument, but could not get it to work.

Sorry, I always seem to have a tough time with scope in JavaScript.

Does anyone know what I could do to be able to access that method from inside the anonymous function from the example page?

Was it helpful?

Solution

I think if you restructured the way the function was defined inside the plugin, it would become quite a bit easier.

Change line 128 from:

var toggleTermHighlighting = function() {

to:

this.toggleTermHighlighting = function() {

Then you can do something like this to access the function from a totally different scope:

var myPlug = new $.fn.searchTermsHighlight();
myPlug.toggleTermHighlighting();

This would be an answer to your question, but I think a different approach might be more appropriate. If you look at a lot of the jQuery UI code, you can pass a string into the plugin and it will execute a function for you. So you could actually just do something like:

$('body').searchTermsHighlight('toggle');

and then just check for it at the top of your function, or in an init() type function

if (options === 'toggle'){ toggleTermHighlighting(); return this; }

OTHER TIPS

You're going to have to make "toggleTermHighlighting" an exposed jQuery function in its own right, or else expose its functionality as an option on your existing method. Well, if you wanted to do something a little weird, you could stuff the function (and anything else you like) into a data element on the affected object (see the jQuery "data" function).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top