Attaching Objects and Data to DOM with jQuery.data - J Query

Problem
Given the following DOM code:

you have metadata associated with a DOM element for easy reference. Because of flawed garbage collection implementations of some web browsers, the preceding code can cause memory leaks.

Solution

Properties added to an object or DOM node at runtime (called expand os) exhibit a number of issues because of flawed garbage collection implementations in some web browsers. jQuery provides developers with an intuitive and elegant method called.data() that aids developers in avoiding memory leak issues altogether:

Discussion
In this recipe, we use the .data() method, which manages access to our data and provides a clean separation of data and markup.
One of the other benefits of using the data() method is that it implicitly triggers get Data and set Data events on the target element. So, given the following HTML:

we can separate our concerns (model and view) by attaching a handler for the set Data event, which receives three arguments (the event object, data key, and datavalue):

The setDataevent is then triggered every time we call .data() on the document element:
// Update the 'time' data on any element with the class 'updateTime'

So, in the previous recipe, every 1 second (1,000 milliseconds) we update the clock dataproperty on the document object, which triggers the setDataevent bound to the document, which in turn updates our display of the current time.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics