[javaScript essay] 03 a simple js agent

Thinking begins with the question:

If the loading time of an A object is difficult to grasp, it is difficult to control when we call other methods.

In this way, we need to make A Proxy object Proxy. When we call the methods above the A object, we can push messages to the Proxy uniformly. The Proxy stores messages in A queue, and then sniffs whether A is loaded. If A is loaded, the Proxy pushes messages in the queue to A.

simple is best ! 

Take a simple example:

The following object is a service object whose loading time cannot be grasped.

// This object is used for processing logic
window.Service = {
    // Load completed identity
    load:true, 
    // add is an array summation method
    add: function(numList, callback){
        var res = 0;
        for(var i = 0; i < numList.length; i++){
            res += numList[i];
        }
        callback.call(this, res);
    }
};

You can call the Service as follows

window.Service.add([1,2], function(res){
    console.log(res);
});

window.Service.add([1,2,4], function(res){
    console.log(res);
});

Based on the above logic, you can simply construct a Proxy

window.Proxyer = {
    queue: [], // Message queue
    isRun: false, // Identification to determine whether sniffing is already in progress
    add: function(numList, callback) {
        this.queue.push({ // Method added to the queue
            numList: numList,
            callback: callback
        });
        if(!this.isRun) { // Prevent repeated sniffing
            this.loopSmell();
        }
    },
    loopSmell: function(){
        var _this = this;
        setTimeout(function(){
            if(!window.Service.load) {
                _this.isRun = true;
                _this.loopSmell();
            }else{
                while(_this.queue.length) { // Processing message
                    var msg = _this.queue.shift();
                    window.Service.add(msg.numList, msg.callback);
                }
                _this.isRun = false;
            }
        }, 0);
    }
};

The above Proxy is not perfect. It simply pushes messages for the Service and the add method.

Then Servie can be called directly, and you don't need to care whether Servie is loaded or not.

window.Proxyer.add([1,2,5,5,5], function(res){
    console.log(res);
});

window.Proxyer.add([1,2,4,5,5,5,5], function(res){
    console.log(res);
});

Added by brailleschool on Sun, 05 Jan 2020 12:39:02 +0200