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

最佳答案

您可以使用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');

关于javascript - MooTools toElement()是否有相反的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11491654/

10-10 23:42