Storing a function with jQuery data() method

Viewed 11087

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?

3 Answers

A better alternative to storing functions in data is using custom events. This can be done easily with on and trigger:

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

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

Example: http://jsfiddle.net/tW66j/

Note: on earlier versions of jQuery (until 1.7), .bind was used instead of .on.

var myFunction = $("#foo").data("say");
myFunction(someParameter);
Related