Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data vs eventData

Tags:

jquery

events

When setting up a event handler (submit, click, keypress, whatever) what is the fastest and most efficient way to get data to the handler and use it in the handler? Should I be doing something like:

$obj.data({name: value, ...});

$obj.click(function(e){
  var $this = $(e.target),
    name = $this.data(name);
});

Or is it better to do something like this:

$obj.bind('click', {name: value}, function(e) {
  var $this = $(e.target),
    name = e.data.name;
});

Are there other considerations I am omitting?

like image 814
craveytrain Avatar asked Jul 14 '10 15:07

craveytrain


1 Answers

Either way works, you're storing the same data in a slightly different spot, though your first can be less wasteful using $.data() without creating a jQuery object, like this:

$obj.data({ name: value });
$obj.click(function(e) {
  var name = $.data(this, 'name');
});

Personally, I find the second much cleaner, it's equivalent version is shorter overall as well:

$obj.bind('click', {name: value}, function(e) {
   var name = e.data.name;
});
like image 179
Nick Craver Avatar answered Oct 18 '22 14:10

Nick Craver