Как запустить индикатор выполнения (который получает% приращения каждые x секунд) параллельно с вызовом ajax? - PullRequest
0 голосов
/ 15 мая 2018

Это часть моего объекта:

const qwData = {

    // Initialize functions
    init: function() {
        this.cacheDom();
        this.bindEvents();
    },
    // Cache vars 
    cacheDom: function() {
        this.dataDisplayed  = false;
        this.countUsers     = <?php echo $_SESSION['all_users_count_real']; ?>;
        this.$form          = $('#frm_reportit');
        this.start_date     = this.$form[0][9].value;
        this.end_date       = this.$form[0][10].value;
        this.dateCount      = this.countDays(this.start_date, this.end_date);
        this.show           = document.querySelector('#btn-show');
        this.downloadBtn    = document.querySelector('#download_summary_button');
        this.$dataContainer = $('#qw-data-container');
        this.$qwTable       = $('#qwtable');
        this.$qwTbody       = this.$qwTable.find('tbody');
        this.qwChart        = echarts.init(document.getElementById('main-chart'));
        this.progressBar    = document.querySelector('.progress-bar');
        Object.defineProperty(this, "progress", {
            get: () => {
               return this.progressPrecent || 0;
            },
            set: (value) => {

                if(value != this.progressPrecent){
                  this.setProgressBarValue(value);
                  this.qwChartProgress = this.returnNumWithPrecent(value);
                }
            }
        });
        this.qwChartProgress= this.progress;
    },
    // Bind click events (or any events..)
    bindEvents: function() {

        var that = this;

        // On click "Show" BTN
        this.show.onclick = this.sendData.bind(this);

        // On Change inputs
        this.$form.change(function(){
            that.updateDatesInputs(this);
        });

    },

sendData: function(e) {
    e.preventDefault();
    let that = this;

    $.ajax({
        type: 'POST',
        url: "/test/ajax.php?module=test_module",
        dataType: 'json',
        data: {
                start_ts: that.start_date,
                stop_ts: that.end_date, 
                submitted: true
        },
        beforeSend: function() {

            // Show Chart Loading 
            that.qwChart.showLoading({ 
                color: '#00b0f0', 
                // text: that.returnNumWithPrecent(that.progress)
                text: that.qwChartProgress
            });

            // If data div isn't displayed
            if (!that.dataDisplayed) {
                // Show divs loading
                that.showMainDiv();
            } else {
                that.$qwTbody.slideUp('fast');
                that.$qwTbody.html('');
            }
        },
        complete: function(){


            let timer = setInterval(that.incrementProgress, 500);

        },
        success: function(result){

            // Set progressbar to 100%
            that.setProgressBarTo100();

            // Show Download Button
            that.downloadBtn.style.display = 'inline-block';

            // Insert Chart Data
            that.insertChartData(result);

            // Insert Table Data
            that.insertTableData(result);
        }
    });

    that.dataDisplayed = true;
},
// Insert Data to Table
incrementProgress: function(){
    this.progress += 10;
},
..... 
.............
....................

Я пытаюсь получить this.progress, чтобы увеличиваться каждые 0,5 секунды на 10% (добавляя 10 к this.progress).Я не уверен, где это сделать и как.Я попытался добавить его к beforeSend: и complete:, но все, что я получил, это 0% -ый индикатор выполнения без каких-либо задержек.Как правильно написать это?

Ответы [ 2 ]

0 голосов
/ 15 мая 2018
Object.defineProperty(this, "progress", {
            get: () => {
               return this.progressPrecent || 0;
            },
            set: (value) => {

                if(value != this.progressPrecent){
                  this.progressPrecent = value;
                  this.setProgressBarValue(value);
                  this.qwChartProgress = this.returnNumWithPrecent(value);
                }
            }
        });

Это была проблема this.progressPrecent = value;

Это всегда было 0, потому что при получении значения оно не устанавливало его в this.progressPrecent.

0 голосов
/ 15 мая 2018

У вас все еще та же проблема.Вот дайджест:

Мое определение теста:

var test = {
    progress: 0,
    increment:function(){
        this.progress = this.progress+10;
    }
}

test is {progress: 0, increment: function}

test.progress();

test is {progress: 10, приращение: функция}

setTimeout(test.increment, 20)

тест равен {прогресс: 10, приращение: функция}, поскольку метод передается по ссылке !!!

setTimeout( function(){test.increment() }, 20)

тест равен {прогресс:20, increment: function}, поскольку контекст сохраняется !!!

Таким образом, даже если ваш таймер запущен правильно, он будет увеличивать прогресс в любом контексте, который не предназначен.

...