[英]Emberjs models with relations throws an error: “Cannot set property 'store' of undefined”
我正在尝试工作中的余烬,看看是否应该在将来的应用程序中使用它。我正在做一个简单的测试应用程序,我想尝试模型之间的关系。 这是我定义模型的代码:
var App = Ember.Application.create();
App.Router.map(function () {
this.resource('index', {path: "/"}, function () {
this.resource("config", {path: "/config/:config_id"});
});
});
App.Store = DS.Store.extend();
App.Conf = DS.Model.extend({
module : DS.attr(),
reports: DS.hasMany('report'),
isClean: function() {
return !this.get('reports').isAny('isClean', false);
}.property('reports.@each')
});
App.Report = DS.Model.extend({
country: DS.attr(),
google_account_id: DS.attr(),
web_property_id: DS.attr(),
custom_source_uid: DS.attr(),
isClean: function() {
return (
this.get('country') != '' &&
this.get('google_account_id') != '' &&
this.get('web_property_id') != '' &&
this.get('custom_source_uid') != ''
);
}.property('country', 'google_account_id', 'web_property_id', 'custom_source_uid')
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://playground.loc/battle_of_frameworks/json.php'
});
…这是正在加载的JSON:
我得到的错误是:
加载路线时出错:TypeError:无法设置未定义的属性“ store”
我用Google搜索了这个问题,通常是将模型命名为复数形式(即App.Reports),而我没有这样做。 所以我不确定这是什么问题。 谁能提供任何见解?
您的代码中有几个问题。
您的服务器未提供Ember Data所需的有效负载。 如果您无法通过后端生成正确的json负载,我建议阅读有关自定义序列化程序的文档 。
Ember.js完全是关于配置的约定。 目前,您没有遵循这些约定:
属性是驼峰式的
App.Report = DS.Model.extend({ googleAccountId: DS.attr() //instead of google_account_id });
您无需创建索引路由, 它在Ember中免费提供 。 因此,您的路由器应该看起来像:
App.Router.map(function () { this.resource("config", {path: "/config/:config_id"}); });
你确定你的后端预计该Config
从送达/config/:config_id
而不是/configs/:config_id
?
您声明config
资源。 约定是具有App.Config
模型而不是App.Conf
为了清除您的代码,您还可以利用计算属性来使代码干燥:
App.Report = DS.Model.extend({
country: DS.attr(),
googleAccountId: DS.attr(),
webPropertyId: DS.attr(),
customSourceUid: DS.attr(),
isClean: Ember.computed.and('country', 'googleAccountId', 'webPropertyId', 'customSourceUid')
});
在基于数组定义计算属性时,还需要注意。 Config
的isClean
使用Report
isClean
,但是您的计算属性仅观察Report
关联的元素。 正确的编写方式是:
App.Config = DS.Model.extend({
module : DS.attr(),
reports: DS.hasMany('report'),
isClean: function() {
return !this.get('reports').isAny('isClean', false);
}.property('reports.@each.isClean') //make sure to invalidate your computed property when `isClean` changes
});
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.