一个进度条类的实现

想实现一个进度条插件。

需求

push()方法将事件推送进事件队列。最后调用finished()进行读取。

progress().push(fn1).push(fn2).finished()

实现问题

  • push() 已经完成,并且finished() 可以推出执行队列,并依次执行。但是每次执行时,总是先完成进度条,然后在执行finished();

  • 程序最好是先执行完push内容,然后加载进度条。然后再进行下一个push内容。

 (function(){
    var progress = function(option){
        return progress.prototype.init(option);
    }
    
    progress.fn = progress.prototype = {
      init: function(option){
          // 初始化
        this.__totel = 0;   // 全部进程数
        this.__index = 0;   // 执行顺序
        this.__fnList = []; // 执行队列

        this.option = this.setOption({
          style: 'bootsrap',
          context: document
        }, option);


        this.creat(this.option.context);
        return this;
      },
      setOption: function(obj, option){
          var i;
        option = option || {};
        for (i in obj){
            if(option[i]){
                obj[i] = option[i] !== obj[i]? option[i] :obj[i];
            }
        }
        return obj;
      },
      creat: function(context){
        $(context).html('<div class="progress progress-striped active"> <div class="progress-bar" style="width: 2%"></div></div>')
        this.option.progress = $('.progress');
        this.option.bar = $('.progress>.progress-bar');
      },
      push: function(fn){
        this.__totel ++;
        this.__fnList.push(fn);
        return this;
      },
      finished: function(){
        for(; this.__index++ < this.__totel;){
          var fn = this.__fnList.shift();
          fn.call(this, this.__index);
        }
      },
      haved: function(i){
        console.log('__index:'+this.__index+',totol:'+this.__totel);
        var progress = this.option.progress,
            bar = this.option.bar;
        bar.css({'width': i/(this.__totel)*100+'%'});

        if(this.__index === 0){
          setTimeout(function(){
            progress.remove();
          }, 600)
        }

      }

使用:

    $('#test').click(function(){
        progress({context: '#content-progress'}).push(function(i){
            this.haved(i)
            setTimeout(function(){
                console.log('i'+i); 
            },1000)

        }).push(function(){
            var d = setTimeout(function(){
                console.log('4');
            },1000)
        }).finished()
    })

结果:

__index:1,totol:2
__index:2,totol:2
i1
2
阅读 1.3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题