开发者

JavaScript OOP problem

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 开发者_JAVA技巧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.


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'


Just use

obj.data = yourData;

to get the data use obj.data


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?


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜