Spo*_*pot 2 javascript oop jquery dom
我正在寻找在同一页面上处理js对象实例时已被发现可接受的模式.(如果有一个线程已经覆盖了这个,那么将会感谢链接.)
这个问题是一个参考问题.在实例化对象/特征之后,必须在稍后的某个时刻引用它.
我已经看到jQuery人员使用存储对目标DOM元素上的对象的引用data().但是,如果可能的话,我对框架无关的选项很感兴趣.
如果有一种干净,可行的方法来为DOM元素生成唯一ID,则可以实现这一点.唉,我还没有找到一个.
所以我的问题是:通过DOM元素存储对象的引用的最佳方法是什么,以便您可以在将来的任意时间引用它?
希望这是有道理的,而且我不仅仅是漫无目的.:)
谢谢.
没有什么可以阻止您维护自己的缓存:
var cache = [];
function locate(el) {
// search for the element within our cache.
for (var i=0;i<cache.length;i++) {
if (cache[i].elem === el) {
return cache[i].data;
};
};
// if we get this far, it isn't in the cache: add it and return it.
return cache[cache.push({
elem: el,
data: {}
}) - 1].data;
};
// used to add data to an element and store it in our cache.
function storeData(el, data) {
var store = locate(el);
for (var x in data) {
store[x] = data[x];
};
};
// used to retrieve all data stored about the target element.
function getData(el) {
return locate(el);
};
Run Code Online (Sandbox Code Playgroud)
然后使用如下:
storeData(document.getElementById("foo"), {
something: 4,
else: "bar"
});
var data = getData(document.getElementById("foo"));
alert(data.something); // "4";
Run Code Online (Sandbox Code Playgroud)