views:

27

answers:

1

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?

+1  A: 

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;
});
Nick Craver
Yeah, I suppose for the example it was irrelevant, I just cut it out of my code where I find I am almost always creating it.
craveytrain