chalo
chalo

Reputation: 1059

Lost the scope of of a function inside a object

I have a problem, I'm losing reference to a property of an object ana when it runs within an event $(window).resize

As I can do to keep the scope.

Example:

var testObject = {

        init: function () {
            this.divOriginal = $('.selector-tag');            
            this.resizeNow();
        },

        resizeNow: function () {
            //some another code here....
            //....
            //..
            $(window).resize(this.resizeUpdate.bind(this)); //without bind(this) the scope is window            
        },

        resizeUpdate: function() {
            console.log($(this));
            var scrollWrapper = $(this)[0].divOriginal;//the only way to refer to the divOriginal 
            scrollWrapper.css('border','1px solid red');
        }
}

testObject.init();

There is a cleaner way to access the object's attributes?

Upvotes: 1

Views: 245

Answers (1)

Matt Musia
Matt Musia

Reputation: 136

You can simply access the object using this instead of $(this) since you bound your object to the method called by the event handler.

See the MDN docs on Function.prototype.bind() :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Upvotes: 1

Related Questions