使用 KnockoutJS 和 Jade 加载 json 文件

Load json file with KnockoutJS and Jade

我有一个 json 文件,我正在通过 api 加载它。 json 文件将是一个商店数组。当我加载页面时,这是我在堆栈跟踪中遇到的错误:

Uncaught ReferenceError: Unable to process binding "foreach: function (){return stores }"
Message: stores is not defined

这是从 API 返回的 json 的样子:

[
    {
        "store_name": "Aber",
        "store_wiki_folder": "#F",
        "store_wiki_contact": "#C",
        "store_wiki_access": "#A",
        "store_db": "db:127.2.3.1:9000",
        "sites": [
            {
                "label": "Prod",
                "link": "http://google.com",
                "special_label": "[Admin]",
                "special_link": "http://images.google.com"
            },

            {
                "label": "Train",
                "link": "http://google.com",
                "special_label": "[Admin]",
                "special_link": "http://images.google.com"
            }
        ]
    },

    {
        "store_name": "Academy",
        "store_wiki_folder": "#F",
        "store_wiki_contact": "#C",
        "store_wiki_access": "#A",
        "store_db": "db:127.2.3.1:9000",
        "sites": [
            {
                "label": "Live",
                "link": "http://google.com",
                "special_label": "[Admin]",
                "special_link": "http://images.google.com"
            },

            {
                "label": "Test",
                "link": "http://google.com",
                "special_label": "[Admin]",
                "special_link": "http://images.google.com"
            }
        ]
    }
]

这是我必须从 api 中提取并进行 ko 绑定的内容:

$.getJSON("/api/stores", function(stores) {
    var storesModel = ko.mapping.fromJSON(stores);
    ko.applyBindings(storesModel);
})

我正在使用 Jade 构建布局:

extends layout

block content
   .container(role="main")
       .row
           .col-md-12
               ul(data-bind="foreach:stores")
                   li(data-bind="text: store_name")

我认为这可能与我构建 json 文件的方式有关。 json 文件的结构可以更改。

"foreach:stores" 假设您在模型中有一个 stores 属性。 你展示的只是一个没有它的数组,所以你需要这样的东西:

ko.applyBindings({ stores: storesModel });