Ad

Mithril.js With Multiple GET Requests

My project was originally in Angular, you can see it on GitHub still. But I'm trying to switch to Mithril.

I'm calling the request on the data.json file (served from GitHub Pages), which is just a list of events ordered by date (ordered at the time of compilation). The load time for the entire file is getting a little questionable, and it's only going to get worse.

My initial solution is to try to load a smaller initial subset of the data (via another file) and then load the rest, but I'm not sure how to do that with Mithril. (Additionally I'll eventually need to do some computation on the data before it's output, if that has any relevance. Like adding attributes to mark year and month boundaries.)

The current relevant code is just this.eventlist = m.request({method: "GET", url: "data.json"}); sitting in the controller. Any suggestions on how I might do this in Mithril (or any suggestion for a better idea) would be appreciated.

Here is the code I have so far:

"use strict",
(function(){
  var app = {};

  app.controller = function() {
    this.eventlist = m.request({method: "GET", url: "data.json"});
  };

  app.view = function(controller) {
    return m("ul", [
      controller.eventlist().map(function(item){
        console.log(item);
        return m("li", [
          m("a", {href: item.url}, item.name),
          m("div", item.description)
        ]);
      })
    ]);
  };

  m.module(document.body, app);

})();
Ad

Answer

I refactored your controller so it has a couple of request functions; init is called on startup, and once it resolves rest is called.

app.controller = function () {
    // changed from this. to var so it's accessible inside the then function
    var eventlist = m.prop([]);

    // load initial data
    var init = function () {
        m.request({method: "GET", url: "first-data.json"}).
            // assign the result to the getter/setter
            then(eventlist).
            // send the request for the rest of the data
            then(rest)
        ;
    };

    // load the rest of the data
    var rest = function () {
        m.request({method: "GET", url: "rest-of-data.json"}).
            // concat the resulting array with the current one
            then(function (result) {
                eventlist(
                    eventlist().concat(result)
                );
            })
        ;
    };

    init();

    // return the eventlist so the view can access it
    return {
        eventlist: eventlist
    }
};
Ad
source: stackoverflow.com
Ad