Reputation: 60997
I've written a plug-in that constructs a rich UI control. I'm hoping that there's a way for me to somehow change how jQuery operate when I query for this element.
I'd like jQuery to be oblivious to the internal structure of this control, but it's not really a hard requirement. What I'd like to do, is to change the meaning of $('#RichUIControlID').val()
to some other function because #RichUIControlID
is the wrapper element for this control (maybe i use a css class to identify that element).
Currently I have to invoke the plug-in function $('#RichUIControlID').richUIControlID().val()
that will return a jQuery object with the necessary changes. val()
does in this case what I want it to do.
However, if I could maintain the jQuery interface without that additional function call it would let me continue to use a familiar pattern which has tremendous reuse value in my case.
// I want to change val() depending on some property of the selector #RichUIControlID
$('#RichUIControlID').val()
Can it be done?
One way to do this thanks to the link provided by mamoo, would be to do it like this then:
(function() {
var val = jQuery.fn.val;
jQuery.fn.val = function() {
if (this.is('#RichUIControlID'))
return this.richUIControlID().val()
else
return val.apply(this, arguments);
}
})();
However, it feels a bit too intrusive. Every call to val()
shouldn't have to check if it's the #RichUIControlID element, I'd rather hook this up during construction if possible.
This is the stuff, browsing the source code it's actually possible to take control of the jQuery constructor in the same manner. The caveat here is that if the first thing you do is not to forward the call to the default constructor, you'll end up with a troublesome call stack.
(function() {
var init = jQuery.fn.init;
jQuery.fn.init = function() {
var q = init.apply(this, arguments); // call this first
if (q.data('RichUIControlID'))
return q.richUIControlID();
else
return q;
}
})();
Upvotes: 1
Views: 424
Reputation: 8166
You can override a JQuery's val() method (see http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm) to implement your own logic, and leave a fallback to the original method if the target object is a standard one.
Upvotes: 2