.replace () вызывает мерцание сайта - PullRequest
0 голосов
/ 15 марта 2020

Я использую mon goose -paginate-v2 на бэкэнде для разбивки ответа из моей БД. Я пытаюсь настроить интерфейс для перемещения по данным и при необходимости отправить запрос на новые данные. (Эта часть, кажется, работает). Проблема, с которой я столкнулся, заключается в том, что DOM, кажется, сходит с ума после нескольких нажатий кнопок «Вперед / Назад». ВИДЕО проблемы, которая находится в конце 20se c vid: (https://drive.google.com/file/d/1btfeKqXELEMmBnFPpkCbBLY5uhrC1bvE/view?usp=sharing)

Что я пробовал: я пробовал .emtpy, .remove и сейчас. заменить все, кажется, имеют ту же проблему. Я также переместил код, чтобы попытаться сделать его до завершения предыдущего .then (). Вот код:

Front End:

<% include ../partials/header%>
<div class="container-fluid pt-3">
    <div class='row'>
        <div class="col-md-1">
            <button class="btn btn-outline-primary sticky-top">Start New Call</button>
        </div>
        <div class="col-md-11">
            <table class="table">
                <thead class="sticky-top">
                    <tr>
                        <th scope="col">Incident #</th>
                        <th scope="col">Type</th>
                        <th scope="col">Location</th>
                        <th scope="col">Units</th>
                        <th scope="col">Dispatch</th>
                        <th scope="col">Clear</th>
                        <th scope="col">Disposition</th>
                        <th scope="col">Recall</th>
                    </tr>
                </thead>
                <tbody id="callTable"> 
                        <tr id="row1"><td></td></tr>
                        <tr id="row2"><td></td></tr>
                        <tr id="row3"><td></td></tr>
                        <tr id="row4"><td></td></tr>
                        <tr id="row5"><td></td></tr>
                        <tr id="row6"><td></td></tr>
                        <tr id="row7"><td></td></tr>
                        <tr id="row8"><td></td></tr>
                        <tr id="row9"><td></td></tr>
                        <tr id="row10"><td></td></tr>
                </tbody>
            </table>
            <div class="row">
                <div class="col-3"></div>

                <div class="text-center col-2">

                    <button id="back" class="btn btn-outline-success mr-auto"><i class="fas fa-step-backward"></i><strong>Back</strong></button>
                </div>
                <div class="justify-content-center d-flex col-2 align-items-center">
                    <strong>Page <span id="pgnum">##</span> of <span id="totalpgs">##</span></strong>
                </div>
                <div class="text-center col-2">
                    <button id="next" class="btn btn-outline-success ml-auto"><strong>Next</strong><i class="fas fa-step-forward"></i></button>
                </div>
                <div class="text-center col-3"></div>
            </div>           
        </div>
    </div>
</div>


<% include ../partials/footer %>

<script>
    //Data Management Script
    let list=[];
    axios.get('/api/cnc/incidents')
    .catch(err=>{
        console.log(err);
    })
    .then(data=>{
        return list=data;
    })

    //Setup Function to get data...

    async function getPage(page){

        axios.get('/api/cnc/incidents/'+page)
    .catch(err=>{
        console.log(err);
    })
    .then(response=>{

        console.log(response);
        calls = response.data.docs;
        callNumber = 'Not Assigned';
            next = response.data.hasNextPage,
            back = response.data.hasPrevPage,
            nextPage = response.data.nextPage,
            prevPage = response.data.prevPage;

        $('#pgnum').text(response.data.page);
        $('#totalpgs').text(response.data.totalPages);

            if(next === true){
                $('#next').removeAttr('disabled');
                $('#next').click(function () { 
                getPage(nextPage);

            });
        }else{
            $('#next').attr('disabled', 'disabled');
        }

        if(back === true){
            $('#back').removeAttr('disabled');
            $('#back').click(function () { 
                getPage(prevPage);

            });
        }else{
            $('#back').attr('disabled', 'disabled');
        }
        // activities.sort((a, b) => b.date - a.date)
        calls.sort((a, b) => (a.times.dispatch > b.times.dispatch) ? -1 : 1)

        return calls;

    }).then(calls=>{
        let i = 1;

            calls.forEach(call => {
            //Set default callNumber.
            callNumber = 'Not Assigned'

            //Update to call number from DB.
            if(call.incidentNumber){
                callNumber = call.incidentNumber;
            }

            //Change _id to Radio ID.
            if(call.units.length > 0){
                let assignedUnits = call.units;
                let idArray = list.data[0];
                const filtered = [];

                function compare(assignedUnits,idArray){
                    assignedUnits.forEach((unit)=>{
                        idArray.forEach((unitId)=>{
                            if(unit === unitId._id){
                                filtered.push(unitId.id);
                            }
                        })
                    })
                    return filtered;
                }                

                compare(assignedUnits, idArray);

               callUnits = filtered.join(', ');

            }else{
                callUnits = ['None']
            }


            if(typeof call.disposition !== 'undefined'){
                callDisposition = call.disposition.selected;
            }else{
                callDisposition = '';
            }

            if(call.times.clear === undefined){

                callClear = '';
            }else{

                callClear = call.times.clear;
            }

            //Insert Data into DOM. and make TR the link to edit

            $('#row'+i).replaceWith('<tr id="row'+i+'" onClick="editRun(\''+call._id+'\')"><th>'+callNumber+'</th><td>'+call.callType+'</td><td>'+call.address.placeName+' '+call.address.streetAddress+'</td><td>'+callUnits+'</td><td>'+call.times.dispatch+'</td><td>'+callClear+'</td><td>'+callDisposition+'</td><td id="recall">'+call.recall.length+' personnel</td></tr>');
            i++;
            });
    })
    }

    //Get the first page of data...
    getPage(1);

    function editRun(runId){
        window.location.href= '/api/cnc/incident/input/'+runId;
    }
   //Update Navbar correctly
   $('document').ready(function(){
        $('.top-nav').removeClass('active').addClass('text-light').removeClass('text-dark');
        $('#incidentTab').addClass('active').addClass('text-dark').removeClass('text-light');    
    });
</script>
...