views:

54

answers:

2

The jQuery .data() documentation says the following:

The .data() method allows us to attach data of any type to DOM element

I assume "any type" refers to functions as well. Say I have a div with the id foo as such:

<div id="foo">Foo!</div>

And I'd like to store a function in it called say that takes a parameter. According to the documentation I'd store the function this way:

$("#foo").data("say", function(message){
   alert("Foo says "+message);
});

My question is, how do I invoke the function with a parameter when I wish to do so.

$("#foo").data("say"); should return the function, but how would I pass a parameter to it?

Thanks!

+2  A: 
var myFunction = $("#foo").data("say");
myFunction(someParameter);
Darin Dimitrov
interesting! i'll give it a try. thanks!
yuval
`$("#foo").data("say")("hello");` seems to work as well.
Kobi
+4  A: 

Storing functions in data feels wrong. Consider creating custom events. This can be done easily with bind and trigger:

$('#foo').bind('say', function(e, arg){
    alert('Foo says ' + arg);
});

$('#foo').trigger('say', 'hello');

Example: http://jsbin.com/ecuco

Kobi
+1 - this is great advice, but Darin answered my question exactly.Thank you very much.
yuval