Question

I have an object where I load some JSON during initialization. I also have a select that I attach an onChange event to. The onChange event function has to work with the object itself, but that object is stale. How do I work with the live or updated object?

var MyFancyObject = {
    init: function() {
        // set controls
        this.abc = // load some stuff async
        this.select.on('change', this.myEvent.call(this)); // attach my event 
    },

    myEvent: function() {
        console.log(this.abc); // undefined
    }
};
Était-ce utile?

La solution

Your event handler is not set up correctly. It is called immediately rather than set up to be called when the event occurs. You can change it to this:

var MyFancyObject = {
    init: function() {
        // set controls
        this.abc = // load some stuff async
        var self = this;
        this.select.on('change', function(e) {
            self.myEvent(e);
        }); // attach my event 
    },

    myEvent: function() {
        console.log(this.abc); // undefined
    }
};

Or, in modern browsers (IE9 or higher), you could use .bind().

var MyFancyObject = {
    init: function() {
        // set controls
        this.abc = // load some stuff async
        this.select.on('change', this.myEvent.bind(this)); // attach my event 
    },

    myEvent: function() {
        console.log(this.abc); // undefined
    }
};

Autres conseils

this.myEvent.call(this) calls the function. Instead you want to bind the function:

    this.select.on('change', this.myEvent.bind(this)); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top