I have two divs in my app and I want them to have custom functions with the same signature, but with different actions, so that I could store the "current" div in a variable, and just call something like:
and have the corresponding methods fired up.
myCurrentDiv.theFunction(someEventData);
How can I do that using jQuery?
I tried doing something like:
$("#myFirstDiv").theFunction = function() {
alert("theFunction on firstDiv");
}
$("#mySecondDiv").theFunction = function() {
alert("theFunction on secondDiv");
}
jQuery's philosophy is opposite to what you want: jQuery doesn't extends any existent types/objects with new attributes or methods; it implements all inside itself.
But if you want to do it with jQuery, you have few different ways:
JavaScript way:
$("#mySecondDiv")[0].theFunction = function(a, b) { /* ... */ }
jQuery.data:
$("#mySecondDiv").data({ theFunction: function(a, b) { /* ... */ } });
$("#mySecondDiv").data("theFunction")(1, 2)
Custom event:
$("#mySecondDiv").bind('my-event', function(event, a ,b) { /* ... */ });
$("#mySecondDiv").trigger('my-event', [1, 2]);
You can use jQuery.data to store data associated with a specific element.
For example:
var div = $("#myFirstDiv")[0];
jQuery.data(div, "theFunction", function() {
alert("theFunction on firstDiv");
});
Looks like what you want is a custom event in jquery...
$('#myFirstDiv').bind('theFunction', function(e) {
alert('theFunction on firstDiv');
});
$('#mySecondDiv').bind('theFunction', function(e) {
alert('theFunction on firstDiv');
});
$('#myFirstDiv').trigger('theFunction');
Here's a working fiddle to show you the example: http://jsfiddle.net/XkutP/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With