0

How can I access the root this inside the events property of the Test object:

"use strict";

var Test = function (element, options) {


};

Test.prototype = {

    constructor: Test,

    events: {

        handleEvent: function (event) {

            // this.setup() should point to the Test.prototype.setup property
        },

        start: function (event) {


        }
    },

    setup: function () {


    }
};

After I use the following syntax to add an event listener to an element:

document.getElementById.addEventListener("touchmove", this.events, false);

Where this.events refers to the Test object. After I tested it, I have noticed that this in that case will be the events object. How can I tweak the code in such way to have the root object available inside the properties of the events object ?

4

1 回答 1

2

You'll have to move the definition of either events, handleEvent or both into the constructor so you will be able to get the right scope to capture the this.
Here is an example..

function EO() {
    this.ev = {      // copy over `handleEvent` and then capture the `this`
        handleEvent: EO.prototype.ev.handleEvent.bind(this) // with bind
    };
};
EO.prototype = {
    ev: {
         handleEvent: function (e) {
             console.log(
                 e,                    // event
                 this,                 // check `this`
                 this.prototype.ev.bar // how to access other properties
             );},
         bar: 'hello!'
    }
}
// construct
var foo = new EO();
// listen
document.body.addEventListener('click', foo.ev);

Now cause some event and you'll see the correct this. If you want to avoid having to access everything through this.prototype, I'd suggest you use a different name for one of the Objects or simply put handleEvent directly in your prototype and not in another Object.

于 2013-07-27T12:43:57.290 回答