Say that I have two html nodes like this:
<div class='node a'>one</div>
<input class='node b' value='two'>
and I’d like to add a method for $(‘.node.a’), but not for node b. What I’d really like to do is something like this:
$('.node.a').addMethod('val', function() {
return $('.node.b').val();
});
alert($('.node.a').val()); // alerts 'two'
Clearly I don’t want to override the ‘val’ method for every jQuery node. Is it possible to do this?
* UPDATE *
As per mgibsonbr’s suggestion, I wrote a jQuery plugin to do this for me. Instead of using jQuery data method, I only run different functionality if the node in question is the one being called. This means that this form will not work for jquery lists that match multiple html nodes. Here it is:
// overrides a method thats supposed to be called on a single node (a method like val)
$.fn.overrideNodeMethod = function(methodName, action) {
var originalVal = $.fn[methodName];
var thisNode = this;
$.fn[methodName] = function() {
if (this[0]==thisNode[0]) {
return action.apply(this, arguments);
} else {
return originalVal.apply(this, arguments);
}
};
};
The only way I know of adding node specific data is using the
datamethod:Not the syntax you wanted, but does the job. Another option is to overload
val, as alex suggested. For instance, you could combine both approaches:This way,
valwould work normally for most items, only behaving differently on those where you manually added a method.