例如,在页面上引用的可接受模式是什么? [英] What are the acceptable patterns for instance referencing on a page?

查看:55
本文介绍了例如,在页面上引用的可接受模式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在同一页面上处理js对象实例时已被发现可接受的模式。 (如果有一个帖子已经覆盖了这一点,我们将非常感谢链接。)

I'm looking for patterns which have been found acceptable when working with instances of js objects on the same page. (If there is a thread already covering this, a link will be appreciated.)

这个问题是参考之一。在实例化对象/特征之后,必须在稍后的某个时间引用它。

The issue is one of reference. After an object/feature is instantiated, it has to be referenced at some point later.

我见过jQuery人员存储对象的引用 on 使用 data()的目标DOM元素。但是,如果可能的话,我对框架无关的选项很感兴趣。

I've seen jQuery people store a reference to the object on the target DOM element using data(). However, I'm interested in a framework agnostic option if possible.

如果有一种干净,可行的方法来为DOM元素生成唯一ID,这可以实现。唉,我还没有找到。

This could be accomplished if there was a clean, viable way to generate an unique id for a DOM element. Alas, I have not found one yet.

所以我的问题是:通过DOM元素存储对象的引用的最佳方法是什么,这样你就可以在未来的任意时间引用它?

So my question is: What is the best way to store reference to an object, via a DOM element, so that you can reference it at a future arbitrary time?

希望这是有道理的,而且我不只是漫无目的。 :)

Hopefully this makes sense, and I'm not just rambling. :)

谢谢。

推荐答案

没有什么可以阻止你维护自己的缓存:

There is nothing stopping you from maintaining your own cache:

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);
};

然后按如下方式使用:

storeData(document.getElementById("foo"), {
    something: 4,
    else: "bar"
});

var data = getData(document.getElementById("foo"));
alert(data.something); // "4";

这篇关于例如,在页面上引用的可接受模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆