How do I show a spinner while waiting for an AJAX request in Mithril JS?

后端 未结 2 1034
忘掉有多难
忘掉有多难 2021-02-08 08:31

I\'m using Mithril JS in a project and I\'m having trouble understanding exactly how to go about hooking into the Ajax lifecycle. Like if I have an Ajax request takes awhile, I

2条回答
  •  暖寄归人
    2021-02-08 09:16

    I found what I think is an elegant way to do this, based on the principle that Mithril re-renders the entire UI (with differencing) on model update. The following example is for saving an inline update.

    When I have some part of the model which is changing via AJAX, I set a temporary flag in the model (you can as easily do it in the view-state model if you want to keep it separate), and on completion, I just delete the flag and invoke m.redraw():

    function updateRecord(ctl,evt,row,idx,rcd) {
        rcd._action="save";
        apiSender({ method: "PATCH", url: apiUrl, data: dropFlags(rcd) }).then(done,fail).then(null,logObject);
    
        function done(rspdta) {
            delete rcd._action;
            m.redraw();
            };
    
        function fail(rspdta) {
            ajaxError(ctl,rspdta,"Update customer "+rcd.CustomerId+" ("+rcd.ContactName+")");
            rcd._action="edit";
            m.redraw();
            };
        }
    

    In the view, which is rebuilt from the model data, I condition on the flag:

    if     (rcd._action=="edit"   ) { con=crtListRecordView_Edit   (rcd,idx             ); }
    else if(rcd._action=="save"   ) { con=crtListRecordView_Waiting(rcd,idx,"Saving"    ); }
    else if(rcd._action=="delete" ) { con=crtListRecordView_Waiting(rcd,idx,"Deleting"  ); }
    else if(rcd._action=="merge"  ) { con=crtListRecordView_Waiting(rcd,idx,"Merging"   ); }
    else if(rcd._action=="refresh") { con=crtListRecordView_Waiting(rcd,idx,"Refreshing"); }
    else                            { con=crtListRecordView_Normal (rcd,idx             ); }
    return m("tr", con);
    

    This allows multiple concurrent actions on different records, and a polished, clear and unobtrusive feedback to the user.

    Here's what it looks like:

    Normal:

    Normal

    Editing:

    Editing

    Saving:

    Saving

提交回复
热议问题