Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla alternative to jQuery $.data() function: any native javascript alternative?

I generally avoid having to include the jQuery library in my scripts, however I only recently came across jQuery $.data()'s functions ability to associate data, in the form of key value pairs, objects & even functions, with any element.

From what I've read, jQuery's $.data() function also has built in safeguards that prevent memory leakage associated with such practices, but it's overkill to include the entire JQ library for that single function.

Does anyone know of a native alternative?

EDIT To make myself more clear, I'm not seeking the native function to retrieve element attributes. jQuery's $.data() API goes far beyond such use, extending to its ability to associate javascript objects & functions with jQuery element nodes.

This article (http://tutorialzine.com/2010/11/jquery-data-method/) touches on this usage, but as an example I currently am using it to associate a GSAP Timeline animation with an object, so that I can access and call GSAP Timeline's .reverse() animation function outside of the function which it is created. For example:

function doAnimation(){
    var element = document.createElement('div'),
        timeline = new TimelineMax({....GSAP related fns...}),
        options = {
            ....
            timeline: timeline
        };
   $(element).data('options', options);
}


function reverseAnimation($element){
    var options = $element.data('options'),
        previouslyCreatedTimeline = options.timeline;

    previouslyCreatedTimeline.reverse();
}

Maybe not the clearest example if you aren't a user of GSAP, but in essence, the $.data() method allowed me to associate a javascript object with an element, so that I can access it's methods in a function outside of its original scope.

like image 598
AJeezy9 Avatar asked Mar 23 '15 23:03

AJeezy9


People also ask

What can replace jQuery () in a function call?

The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.

What is JavaScript vanilla?

Vanilla JavaScript refers to using plain Javascript without any additional libraries or frameworks. The term became popular when Eric Wastl created the Vanilla JS site in 2012 as a joke. The site tries to bring attention to the fact that you can use just plain Javascript in many cases.


1 Answers

I've written a wrapper around WeakMap and Map, that should do the job. The nice thing about WeakMap is, that the value gets GarbageCollected, once the Element is deleted. This should avoid memory leaks.

/** A storage solution aimed at replacing jQuerys data function.
 * Implementation Note: Elements are stored in a (WeakMap)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap].
 * This makes sure the data is garbage collected when the node is removed.
 */
window.dataStorage = {
    _storage: new WeakMap(),
    put: function (element, key, obj) {
        if (!this._storage.has(element)) {
            this._storage.set(element, new Map());
        }
        this._storage.get(element).set(key, obj);
    },
    get: function (element, key) {
        return this._storage.get(element).get(key);
    },
    has: function (element, key) {
        return this._storage.has(element) && this._storage.get(element).has(key);
    },
    remove: function (element, key) {
        var ret = this._storage.get(element).delete(key);
        if (!this._storage.get(element).size === 0) {
            this._storage.delete(element);
        }
        return ret;
    }
}

Use it like this:

var myElement = document.getElementById("myId");
dataStorage.put(myElement, "myKey", "myValue");

This is much faster than $.data(), but still a little slower than storing information as a property at an element.

like image 185
htho Avatar answered Sep 21 '22 09:09

htho