Lucky Soni
Lucky Soni

Reputation: 6878

Access jQuery object inside a function bound to another object

var obj = {
    someFunction : function() {
        $('#someID').on('change', '#someOtherId', function(e) {
            this.someOtherFunction(); // works fine
        }.bind(this));
    },

    someOtherFunction : function() {
        // do something
    }
}

The above piece of code works fine but i am not sure how to access the jQuery wrapped element using $(this) inside the someFunction. Help is appreciated.

Upvotes: 0

Views: 98

Answers (2)

justtal
justtal

Reputation: 800

I think that the clean way is to use $.proxy

var obj = {
    someFunction : function() {
        $('#someID').on('change', '#someOtherId', $.proxy(this.someOtherFunction, this));
    },

    someOtherFunction : function(e) {
        //this is the jquery $(this) element
        var $el = $(e.currentTarget);

        //the "this" is the main "obj" object
    }
}

On a anonymous callback function:

    var obj = {
        someFunction : function() {
            $('#someID').on('change', '#someOtherId', $.proxy(function (e) {
                //this is the jquery $(this) element
                var $el = $(e.currentTarget);

                //the "this" is the main "obj" object
                this.someOtherFunction();
            }, this));
        },

        someOtherFunction : function(e) {

        }
    }

Upvotes: 2

sjkm
sjkm

Reputation: 3937

var obj = {
    someFunction : function() {
        var me = this;
        $('#someID').on('change', '#someOtherId', function(e) {
            var $elem = $(this); // element / jquery object
            me.someOtherFunction(); // works fine
            // me is assigned in "obj" scope 
        });
    },

    someOtherFunction : function() {
        // do something
    }
}

Upvotes: 4

Related Questions