MooTools toElement()有相反的方法吗?

时间:2012-07-15 11:54:49

标签: javascript mootools

我很高兴使用MooTool的toElement(),它能够跟踪哪个DOM元素属于我的类的某个实例。有没有办法扭转这种行为?如:给它一个元素并获得它所属的类的实例的引用?

1 个答案:

答案 0 :(得分:2)

您可以使用Element.store()Element.retrieve()方法在DOM元素上存储和检索对象引用。

你的课可以是例如:

var MyClass = new Class({

    initialize: function(element) {
        this.el = document.id(element); // Store element for later usage

        // Store a reference to "this" object on the Element itself
        this.el.store('_MyClass', this);

        return this;

    },

    // Object -> Element (you already know this)
    toElement: function() {
        return this.el;
    }

});

// The following implements a new property for all Elements (optional)
Element.Properties.myClass = {

    get: function() {
        return this.retrieve('_MyClass');
    }

};

然后,检索附加到DOM元素的对象实例:

// Object creation
new MyClass($('some_element'));

// The easy way, if you did not implemented Element property
var myClassInstance = $('some_element').retrieve('_MyClass');

// Or prettier, if you implemented property like I showed you
var myClassInstance = $('some_element').get('myClass');