Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top