Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a function with jQuery data() method

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!

like image 254
Yuval Karmi Avatar asked Feb 01 '10 07:02

Yuval Karmi


People also ask

What is the use of jQuery data () method?

The . data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr .

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

How set data attribute in jQuery?

It should be noted that jQuery's data() doesn't change the data attribute in HTML. So, if you need to change the data attribute in HTML, you should use . attr() instead.


2 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.

like image 181
Kobi Avatar answered Sep 21 '22 15:09

Kobi


var myFunction = $("#foo").data("say"); myFunction(someParameter); 
like image 29
Darin Dimitrov Avatar answered Sep 24 '22 15:09

Darin Dimitrov