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

后端 未结 2 502
北荒
北荒 2021-02-08 08:59

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:10

    One way is to wrap m.request in another function that returns both the completion state (based on a flag that you set via the m.request promise chain), and the data, and then use the background: true option to prevent the deferral of the redraw, and also bind m.redraw to the promise chain in order to have redrawing happen after the request.

    This was originally described here: https://github.com/lhorie/mithril.js/issues/192

    var requestWithFeedback = function(args) {
      var completed = m.prop(false)
      var complete = function(value) {
        completed(true)
        return value
      }
      args.background = true
      return {
        data: m.request(args).then(complete, complete).then(function(value) {
          m.redraw()
          return value
        }),
        ready: completed
      }
    }
    
    var MyController = function() {
      this.things = requestWithFeedback({method: "GET", url: "/things"})
    }
    var myView = function(ctrl) {
      return !ctrl.things.ready() ? m("img[src=loading.gif]") : m("ul", [
        ctrl.things.data().map(function(thing) {
          return m("li", thing.name)
        })
      ]) 
    }
    
    m.module(document.body, {controller: MyController, view: myView})
    

提交回复
热议问题