문제

I try to understand the following code. To be precise, the study method $.proxy(). Everything was clear until I got this script:

(function($, exports){
    var mod = function(){};
    mod.fn  = mod.prototype;

    mod.fn.proxy = function(func){
        return $.proxy(func, this);
    };
    mod.fn.load = function(func){
        $(this.proxy(func));
    };
    exports.Controller = mod;
})(jQuery, window);

(function($, Controller){
    var mod = new Controller;
    mod.toggleClass = function(e){ 
        this.view.toggleClass("over", e.data);
    };
    mod.load(function(){
        this.view = $("#view");
        this.view.mouseover(this.proxy(this.toggleClass));
        this.view.mouseout(this.proxy(this.toggleClass));
    });
})(jQuery, Controller);

And I do not understand how $.proxy() works in this part:

mod.fn.load = function(func){
    $(this.proxy(func)); // Why it is converted into an object jQuery?
};

Can anyone explain how this works?

도움이 되었습니까?

해결책

it is not a jQuery object, $(this.proxy(func)); is registering the function passed to the load method as a dom ready handler so that even if the load method is called before dom is ready is callback function is delayed till the dom is ready. If the dom is already in ready state then the callback is executed without any delay.

mod.fn.load = function (func) {
    console.log('inside load')
    $(this.proxy(func));
    console.log('exit load')
};

Demo: Fiddle

It is the same as

mod.fn.load = function (func) {
    var self =  this;
    //dom ready callback
    $(function(){
        func.call(self);
    });
};

Demo: Fiddle


If you are not doing so then there is a possibility that the script will fail like

mod.fn.load = function (func) {
    var self =  this;
    console.log('inside load');
    func.call(self);
    console.log('exit load')
};

Demo: Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top