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?
Use
applyand theargumentsobject:to call
extOnSelectexactly like the current function.You could use
call, but then you would need to pass the event object (and other possibe arguments) explicitly.