[英]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.