Search code examples
javascriptjquerystorecustom-events

jQuery: storing data between custom events


Given the following example ...

$("#some-id").on("custom-event-1", function()
{
  this.someData = "test";
}).on("custom-event-2", function()
{
  var test = this.someData;
  ...
});

... I am able to store and pass data between custom-event-1 and custom-event-2, however, is this the correct way of doing this? It works, but I'm not sure if things should be done this way, or if the jQuery data method should be used instead. If this approach is acceptable, where exactly is the data being stored? I understand where the jQuery data method stores the data, but the example above I'm not sure about.


Solution

  • I'd recommend you to use .data(id,value).

    DOM elements are like a regular object. Ex: A div is an instance of the prototype HTMLDivElement. Test it via document.createElement('div').constructor.

    Doing this.someData = 1 is similar to a = new Date(); a.someData = 1 or a = []; a.someData = 1.

    It does work but it's not "clean". There is a performance cost to change the structure of an object. And you assume that the object doesn't have the attribute someData already used for something else.

    With .data() you are safe.