如何在Mithril JS中等待AJAX​​请求时显示微调器?

时间:2014-08-18 20:36:29

标签: javascript ajax mithril.js

我在一个项目中使用Mithril JS而且我很难理解如何进入Ajax生命周期。就像我有一个Ajax请求需要一段时间,我想展示一个微调器。非常基本,但我似乎无法弄清楚这是怎么发生的。

我想为微调器使用相同的容器作为Ajax请求所寻找的内容。

这是我的设置:

var Thing = function (data) {
  var p = m.prop;
  this.title = p(data.title);
  this.timestamp = p(moment.unix(data.timestamp));
}

Thing.list = function(options) {
  m.request({method: "GET", url: "/things.json", type: Thing, background: true});
};

MyApp.components.thingsList = {
  controller: function ThingListController() {
    this.things = m.prop([]);
    Thing.list().then(this.things).then(m.redraw);
  },

  view: function thingListView(ctrl) {
    return m('div#thing-tab', [
      m('ul#things', [
        ctrl.things().map(thingView)
      ])
    ]);
  }
};

function thingView(thing) {
  ...some view stuff...
}

我已经按照我想要的方式工作,但我无法弄清楚如何挂钩到ajax生命周期。同样,我只是想在请求开始时显示一个微调器,然后将其替换为ajax请求的结果。

非常感谢任何和所有帮助!

谢谢,

2 个答案:

答案 0 :(得分:11)

一种方法是将m.request包装在另一个函数中,该函数返回完成状态(基于您通过m.request promise链设置的标志)和数据,然后使用{{1 }}选项以防止重绘的延迟,并将background: true绑定到promise链,以便在请求之后重新绘制。

最初在此处描述:https://github.com/lhorie/mithril.js/issues/192

m.redraw

答案 1 :(得分:2)

我发现我认为这是一种优雅的方式,基于Mithril在模型更新中重新渲染整个UI(带差分)的原则。以下示例用于保存内联更新。

当我通过AJAX更改模型的某些部分时,我在模型中设置了一个临时标志(如果要将它保持分离,可以在视图状态模型中轻松完成),并在完成时,我只是删除标志并调用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();
        };
    }

在从模型数据重建的视图中,我对标志进行了调整:

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);

这允许对不同记录进行多个并发操作,并为用户提供精美,清晰且不显眼的反馈。

这就是它的样子:

正常:

  

Normal

编辑:

  

Editing

保存:

  

Saving

相关问题