2

A project I am working on for works wants a pure JavaScript version of the .data() implementation of jQuery.

I wanted to replicate this.

I did a search and Where is jQuery.data() stored? shows where in jQuery it is stored.

I was hoping that i could just attach a datasegment to an HTML element for accessing later.

Since jQuery is Javascript, I can look there, but it makes use of the jQuery objects, which is what I am trying to abstract. I figured there was some sort of way to associate a hash table like dataset with JavaScript and attach it to an object.

Community
  • 1
  • 1
Fallenreaper
  • 10,222
  • 12
  • 66
  • 129

1 Answers1

3

http://jsfiddle.net/npXQx/

shows you can create a .data in the object and then it is preserved. You can access it twice, and the data is there.

This example shows a simple string assignment and a function and it being called multiple times.

var item = document.getElementById("hi");
console.log(item);

item.data = {getType: function(){return this.TYPE},TYPE:"winner"};

var out = item.data.getType();
console.log("out", out);

var two = document.getElementById("hi")
console.log("should say 'winner': ", two.data.getType());
Fallenreaper
  • 10,222
  • 12
  • 66
  • 129