$ .proxy()未按预期工作。我怀疑它不适用于嵌套对象

时间:2014-03-18 18:39:02

标签: javascript jquery

我首先通过阅读bootstrap.js源代码了解了这个函数。如果你不熟悉,这里是document

通过多次试验和错误,我发现$ .proxy()不适用于多级对象。这是真的?这是我的代码:

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');

}

我认为这行代码存在问题:

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

你能帮我诊断一下这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:1)

问题是你有这个:

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

这将导致这种情况发生:

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

this不是jQuery对象,使用该上下文调用css将无效。

你需要这个:

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

但是,我不明白为什么你这样做,如果你希望你的reset方法做的唯一事情就是更改对象的CSS属性。您可以通过以下方式实现相同目标:

ProgressBtn.prototype.reset = function(ms) {
    this.$progressIndicator.css({'background-color': 'red'});
};
当您想要将处理程序附加到事件,并且希望使用特定上下文(如.NET委托)执行该处理程序时,

$.proxy非常有用