Nicolas S.Xu
Nicolas S.Xu

Reputation: 14534

$.proxy() is not working as expected. I suspect it doesn't work on nested object

I first learned about this function by reading bootstrap.js source code.If you are not familar, here is the document.

Through multiple trial & error, I found out $.proxy() doesn't work for multi level object. Is this true? Here is my code:

ProgressBtn.prototype.reset = function(ms) {
        var self = this;
            //this.$progressInicator is a jquery object
        // here is the problem: reset() call is not working, nor displaying error
            var reset = $.proxy( this.$progressIndicator.css, 
                        this, 
                        {'background-color': 'red'}
            );          
            reset();
        console.log('reset is running');

}

I think this line of code has problem:

var reset = $.proxy( this.$progressIndicator.css, 
                     this, 
                     {'background-color': 'red'}
            );

Can you help me diagnose the problem? Thanks!

Upvotes: 0

Views: 45

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

The problem is that you have this:

var reset = $.proxy( this.$progressIndicator.css, 
    this, 
    {'background-color': 'red'}
);

This will basicall cause this to happen:

this.$progressIndicator.css.call(this, {'background-color': 'red'});

But this is not a jQuery object, calling css with that context will have no effect.

You need this:

var reset = $.proxy( this.$progressIndicator.css, 
    this.$progressIndicator, 
    {'background-color': 'red'}
);

However, I don't understand why you are doing this this way, if the only thing you want your reset method to do is to change a CSS property of an object. You could achieve the same with:

ProgressBtn.prototype.reset = function(ms) {
    this.$progressIndicator.css({'background-color': 'red'});
};

$.proxy is useful when you want to attach a handler to an event, and you want that handler to be executed with a specific context (like a .NET delegate)

Upvotes: 1

Related Questions