2

Let's say I have a jquery plugin that has an onSelect attribute. The user sets it to a function, and when that function is called, this refers to the object the plugin is applied to. All is good.

If I want to write a plugin that wraps this plugin, in order to inject some code into the onSelect, I do something like this:

// Get whatever the user put in
var extOnSelect = options['onSelect'];

// delete the onSelect attribute
delete options['onSelect'];

// re-add onSelect as an anonymous function that calls my method and the user's
var options = $.extend({ 
    'onSelect': function() { onSelect(); extOnSelect(); }
    }, options);

// call the plugin that I am wrapping / injecting extra onSelect code into
$(this).externalPlugin(options);

Then it will pass in my own onSelect code, while preserving what the user entered.

The only problem is, within each of those two functions this no longer refers to the object, it now refers to I think the generic inline function.

What's the best solution to fix this?

0

2 Answers 2

3

Use apply and the arguments object:

extOnSelect.apply(this, arguments);

to call extOnSelect exactly like the current function.

You could use call, but then you would need to pass the event object (and other possibe arguments) explicitly.

3
  • Thanks, what would 'arguments' refer to in this case?
    – NibblyPig
    Oct 18, 2012 at 10:20
  • arguments is an array-like object which contains the current arguments. In your case - the event handler - it would contain one item, the [jQuery] event object.
    – Bergi
    Oct 18, 2012 at 10:23
  • Worked great - the event handler actually triggers with some arguments and they're passed along nicely for me to use! Thanks!
    – NibblyPig
    Oct 18, 2012 at 11:18
1

I think you need to use call method of javascript functions.

var options = $.extend({ 
'onSelect': function() { onSelect.call(this); extOnSelect.call(this); }
}, options);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.