Ember.js从API加载简单数据

时间:2013-05-06 06:55:00

标签: javascript ember.js ember-data

所以,我有一个Ember.js的简单页面,我正在尝试从rest api加载数据。

Api由apiary.io提供,并返回以下简单数据

{"semantics": [
 {key : "11111", name : "Block 1"},
 {key : "22222", name : "Block 2"},
 {key : "33333", name : "Block 3"},
 {key : "44444", name : "Block 4"},
 {key : "55555", name : "Block 5"}
]}

问题是通过App.Semantic.find()获取数据的模型,它不会将项目放到模板中。

但如果我在路由

中设置数组值,它会按预期工作
App.SemanticRoute = Ember.Route.extend({
    model: function () {
        //return App.Semantic.find();
        return [{key:111,name:"aaaa"},{key:222,name:"qqqqq"},
                {key:3333,name:"bbbb"},key:555,name:"ccc"}];
    }
});

问题出在哪里?

指向API的链接 - http://bug0r.apiary.io/api/semantics

带有代码的jsFiddle - jsfiddle

这里的完整代码

var App = window.App = Ember.Application.create({
    VERSION: '1.0',
    rootElement: '#appRoot',
    LOG_TRANSITIONS: true
});
App.deferReadiness(); // do not initialize it until we are ready

App.Adapter = DS.RESTAdapter.extend({
    namespace: 'api',
    url: 'http://bug0r.apiary.io'
});
App.Adapter.map('Semantic', {
    primaryKey: 'key'
});
App.Store = DS.Store.extend({
    revision: 12,
    adapter: App.Adapter
});

App.Router.map(function () {
    // each call will create Ember.Route instance for customizing route
    this.resource("semantic", {
        path: "/"
    });
    this.route("about", {
        path: "/about"
    });
});

/* Symantic model*/
App.Semantic = DS.Model.extend({
    key: DS.attr('string'),
    name: DS.attr('string'),
});

App.SemanticRoute = Ember.Route.extend({
    model: function () {
        return App.Semantic.find();
    }
});

App.advanceReadiness(); // ready for initialization

编辑: 1. JSON api已修复,但仍无效。

1 个答案:

答案 0 :(得分:1)

API返回无效的JSON(键值不应由=分隔,而应由:分隔,属性应用引号括起来

{ "semantics": [
{key = "11111", name = "Block 1"},
{key = "22222", name = "Block 2"},
{key = "33333", name = "Block 3"},
{key = "44444", name = "Block 4"},
{key = "55555", name = "Block 5"}
] }

应该是

{ "semantics": [
{"key":"11111", "name":"Block 1"},
{"key":"22222", "name":"Block 2"},
{"key":"33333", "name":"Block 3"},
{"key":"44444", "name":"Block 4"},
{"key":"55555","name":"Block 5"}
] }