javascript - Mithril.js 具有多个 GET 请求

标签 javascript json ajax github-pages mithril.js

我的项目最初是用 Angular 编写的,you can see it on GitHub still 。但我正在尝试切换到 Mithril 。

我正在 data.json 文件(从 GitHub Pages 提供)上调用请求,该文件只是按日期排序的事件列表(在编译时排序)。整个文件的加载时间变得有点可疑,而且只会变得更糟。

我最初的解决方案是尝试加载数据的较小初始子集(通过另一个文件),然后加载其余部分,但我不确定如何使用 Mithril 来做到这一点。 (此外,如果有任何相关性,我最终需要在输出数据之前对数据进行一些计算。例如添加属性来标记年和月边界。)

当前的相关代码只是位于 Controller 中的 this.eventlist = m.request({method: "GET", url: "data.json"}); 。任何关于我如何在 Mithril 中做到这一点的建议(或任何更好的想法的建议)将不胜感激。

这是我到目前为止的代码:

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

})();

最佳答案

我重构了你的 Controller ,使其具有几个请求功能; init 在启动时调用,一旦解析完毕,rest 就会被调用。

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

关于javascript - Mithril.js 具有多个 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487148/

相关文章:

javascript - 使用 cookie 保存切换状态 + 类切换

javascript - 服务器首次启动时创建一次 JSON 文件

Javascript - 迭代无键 JSON

javascript - ASP.NET Ajax 出现错误,代码为 0

javascript - 安全的 ajax 脚本(javascript 请求的 PHP 脚本)

javascript - 如何在 Node js 应用程序中执行 jar 文件

javascript - JavaScript 的版本号是多少,对应的 ECMAScript 版本是多少?

javascript - 如何在 appium 的 webdriverio 中使用驱动程序对象

javascript - AngularJS ng-repeat 具有多个显示不同值的列表

javascript - 从 php 返回多个值到 jquery