开发者

Help with calling an internal method of a jQuery plugin [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

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.toggl开发者_运维百科eTermHighlighting = 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?


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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜