tags:

views:

69

answers:

4

I create windows like this:

var obj = document.createElement('div'); 
obj.className = 'window';
obj.style.width = 300 + 'px';
obj.style.height = 200 + 'px';
obj.style.left = 30 + 'px';
obj.style.top = 200 + 'px';     

//and so on

and what I need is to attach some data to each window. The data will be grabbed via Ajax and displayed in the windows. How should I do it so that each window hold its own unique data?

I don't need to display the whole data every time and this data would need be organized before being displayed, so I can't just add it with innerHTML. I need a way to hold it somewhere else where I could easily get it and then display it with innerHTML.

A: 

A wild guess -

obj.data = 'Whatever'

And later

obj.innerHTML = format(obj.data);

I tried this in my Firebug console, worked there. Maybe worth trying in others?

Lauri Lehtinen
A: 

Just use

obj.data = yourData;

to get the data use obj.data

Fopfong
things are case-sensitive, so you mean "obj.data", not "obj.Data"
Pointy
@Pointy Yes!, thank you :D
Fopfong
+1  A: 

Could you use jQuery? jQuery has something called data so in your example you could do:

var obj = $('<div></div>');  
obj.addClass('window');  
obj.data('foo', 'setting some data here');

you can access your data later on with:

obj.data('foo') // will return 'setting some data here'
Michal Kuklis
+1 yeah! jQuery for everything.. ;)
Reigel
A: 

You could build your own constructor function to create your own window objects and store the DOM element and the data on each instance, e.g.:

function MyWindow (width, height /*, ...*/) {
  var data = {}; // here the data will be stored
  // the DOM element
  this.element = document.createElement('div'); 
  this.element.className = 'window';
  //...
  // a method for get and set key/value pairs:
  this.data = function (key, value) {
    if (typeof value == 'undefined') {
      return data[key];
    } else {
      data[key] = value;
      return this;
    }
  };
}

MyWindow.prototype.sharedMethod = function () {
 // shared across all instances, you can access here public members
 // like the `this.data` method and the `this.element` DOM element
};

Example usage:

var win1 = new MyWindow(300, 200);
win1.data('key1', 'value1').data('key2', 'value2'); // chainable method :)

// to access the DOM element:
win1.element;

// to get the values
win1.data('key1'); // "value1"
win1.data('key2'); // "value2"

var win2 = new MyWindow(300, 200);
win2.data('someData', {foo: 'bar', baz: true});
win2.data('someData').foo; // "bar"
CMS