Home > Web Front-end > JS Tutorial > Successfully solved the custom event and solved the bug of repeated requests

Successfully solved the custom event and solved the bug of repeated requests

巴扎黑
Release: 2017-07-22 15:32:38
Original
1535 people have browsed it

Nowadays, component-based development is still quite popular, after all, its advantages are quite prominent. Recently, when developing a component, I encountered a very interesting BUG. . .

Background of BUG

Recently I was developing a component, and it was finally developed and tested. Then, the test mentioned a bug like this to me, orz...

#Because it is a component, the biggest advantage is that it can be reused and used anywhere. However, When a page uses multiple components and only the last one takes effect, this component is meaningless. . .

BUG cause search

The interface of the initial data source of this component is fixed, that is to say, all components in the page will issue the same message during initialization. The request here is in the form of jsonp, so the callback function is a function bound to the window, but there is only one window in the page, so when the callback is processed, the corresponding data in the component to be processed only points to The last component. As a result, multiple identical components are placed on the same page, and only the last component can be rendered successfully after obtaining the data.

BUG solution idea

The most important thing is to store the callback of each request, so as to ensure that the processing of component data in the callback does not only point to the last one . Secondly, since it is the same request, of course we do not want it to be issued more than twice, that is, every request issued by a page is unique.

BUG Solution

I thought of publishing custom events in subscriber mode. You can write such a module to determine whether there is the same event before each request is issued. The module has been issued. If not, the cache callback will issue the request. If the same request has been issued, then check whether the issued request has been completed. If not, continue to cache the callback and wait. If the request has been issued and completed Then handle the callback directly. After the request comes back for the first time, a broadcast is issued and all previously cached callbacks are executed.

Custom event details

Define a module with n event objects named after callback functions. When each object is initialized, its State, the corresponding callback array, and the data returned by the request. Each time this module is called, first check whether the corresponding cbName is initialized, and then check its state. Perform corresponding operations according to the state and change the value of the state. There are three values ​​of state, namely init, loading, and loaded. That is, initializing, requesting, and requesting completion. The corresponding callback can only be executed when the request is completed. The details are as follows:

define('wq.getData', function (require, exports, module) {
    var ls = require('loadJs');
    
    var cache = {};
    cache.init = function(cb,cbName,url){
        if(!cache[cbName]){
            cache[cbName] = {};
            cache[cbName].state = 'init';
            cache[cbName].cbs = [];
            cache[cbName].data = [];
        }
        cache.on(cb,cbName,url);
    }
    cache.on = function(cb,cbName,url){
        if(cache[cbName].state == 'loaded'){
            cb(cache[cbName].data)
        }else if(cache[cbName].state == 'loading'){
            cache[cbName].cbs.push(cb)
        }else if(cache[cbName].state == 'init'){
            cache[cbName].cbs.push(cb);
            cache[cbName].state = 'loading';
            cache.fetch(cb,cbName,url);
        }
    }
    cache.broadcast = function(cbName){
        cache[cbName].cbs.forEach(function(cb){
            cb(cache[cbName].data)
        });
    }
    cache.checkLoaded = function(cbName){
        if(cache[cbName].data[0]){
            cache[cbName].state = 'loaded';
            cache.broadcast(cbName);
        }
    }
    cache.fetch = function(cb,cbName,url){
        ls.loadScript({
            url: url,
            charset: 'utf-8',
            handleError:function(func, args, context,errorObj){
                console.log(_errlogText + context);
                cache[cbName].data[0] = {};
                cache.checkLoaded(cbName);
            }
        });
        if(window.cbName) return;
        window[cbName] = function(json){
            cache[cbName].data[0] = json;
            cache.checkLoaded(cbName);
        }
    }

    exports.getData = function(cb,cbName,url){
        cache.init(cb,cbName,url);
    }  

})
Copy after login

Perfectly solves the problem, each callback will not be missed or overwritten...

Expand ideas

This module can be used universally to handle the same request within a page. It can also be extended to handle situations that require more than two requests to be completed before executing a certain callback. Similar to the case of Promose. At this time, it can be stipulated that each data[0] contains fixed data corresponding to the interface, data[2] corresponds to another one, and so on. However, this requires traversing until each item is true before executing the callback. Moreover, the corresponding relationship is easy to be confused, and it is better to use Promise to handle it if you expand it further. . .

The above is the detailed content of Successfully solved the custom event and solved the bug of repeated requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template