TypeError:无法设置undefined的属性'store'

时间:2014-02-28 09:58:43

标签: ember.js ember-data

我在使用ember-data在ember js中加载模型实例时遇到问题。使用函数store.find时抛出异常。使用FixtureAdapter创建实例。在模型中定义hasMany关系时会出现问题。

App = Ember.Application.create();

App.Store = DS.Store.extend({
    adapter: DS.FixtureAdapter
});

App.Country = DS.Model.extend({
    'name': DS.attr('string'),
    'cities': DS.hasMany('city', {embedded: true})
});

App.City = DS.Model.extend({
    'name': DS.attr('string'),
    'country': DS.belongsTo('country')
});

App.City.FIXTURES = [{
}];

App.Country.FIXTURES = [{
    'id': 1,
    'name': 'USA',
    'cities': [{id: 1, name: 'New York'}, {id: 2, name: 'San Francisco'}]
},{
    'id': 2,
    'name': 'Kanada',
    'cities': [{id: 3, name: 'Montreal'}]
}];

App.IndexRoute = Ember.Route.extend({
    model: function() {
        var store = this.store;
        var country = store.find('country', 1);
        return country;
    }
});

http://jsfiddle.net/xSq4y/

DEBUG: ------------------------------- ember.js:3496
DEBUG: Ember      : 1.5.0-beta.2 ember.js:3496
DEBUG: Ember Data : 1.0.0-beta.7.f87cba88 ember.js:3496
DEBUG: Handlebars : 1.3.0 ember.js:3496
DEBUG: jQuery     : 2.1.0 ember.js:3496
DEBUG: ------------------------------- ember.js:3496
Error while loading route: TypeError: Cannot set property 'store' of undefined
    at Ember.Object.extend.modelFor (http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:9812:23)
    at Ember.Object.extend.recordForId (http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:9265:21)
    at deserializeRecordId (http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:10196:27)
    at deserializeRecordIds (http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:10210:9)
    at http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:10176:11
    at http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:8517:20
    at http://builds.emberjs.com/tags/v1.5.0-beta.2/ember.js:3403:16
    at Object.OrderedSet.forEach (http://builds.emberjs.com/tags/v1.5.0-beta.2/ember.js:3246:10)
    at Object.Map.forEach (http://builds.emberjs.com/tags/v1.5.0-beta.2/ember.js:3401:10)
    at Function.Model.reopenClass.eachRelationship (http://builds.emberjs.com/tags/v1.0.0-beta.7/ember-data.js:8516:42) 

1 个答案:

答案 0 :(得分:0)

如果您的API以该格式返回数据,您可以使用序列化程序将其转换为Ember Data期望的格式。试试这个:

App.CountrySerializer = DS.RESTSerializer.extend({
  normalizePayload: function(type, payload) {
    var tempCities = payload.country.cities;
    payload.country.cities = [];
    tempCities.forEach(function(city) {
      payload.country.cities.push(city.id);
    });
    payload.cities = tempCities;
    return this._super(type, payload);
  },
})