我正在为 Ember 数据滚动一个 localStorage 适配器,当我运行 find 函数时,即:
App.store.find(App.Person, 0 );
我收到此错误:
Uncaught Error: assertion failed: A data hash was loaded for a model of type App.Person but no primary key 'undefined' was provided.
在更一般的层面上,我对“持久层”(在本例中为 localStorage )和 Ember 存储之间的关系有点困惑。将东西加载到商店是什么意思?这是否意味着 DS.Person 模型的实例是用数据创建的?
另外,如果您注意到我在 createRecord 方法中注释掉了一行“App.store.didCreateRecord(model, data)”,因为它也不起作用。如果在记录加载到 localStorage 后我不调用 store.didCreateRecord 会发生什么。
细节:
DS.LocalStorageAdapter = DS.Adapter.extend({
get: Ember.get,
set: Ember.set,
createRecord: function( store, modelType, model ){
var records, index, data;
// get existing records of this model
records = this.localStorage.get( modelType );
index = records.length;
data = this.get( model, 'data' );
// set storageID of data
data.set( 'storageID', index );
// add data to existing records
records[index] = data;
// encode records
records = JSON.stringify( records );
// store records in localStorage
this.localStorage.set( modelType, records );
// App.store.didCreateRecord( model, data );
},
find: function( store, modelType, id ) {
var records, model;
records = this.localStorage.get( modelType );
model = records[id];
App.store.load( modelType, model );
},
localStorage: {
set: function( modelType, value ){
localStorage.setItem( modelType, value);
},
get: function( modelType ){
var record = localStorage.getItem(modelType);
record = JSON.parse(record) || [];
return record;
}
}
});
//application model
App.Person = DS.Model.extend({
name: DS.attr('string', {key: 'css_name'}),
storageID: DS.attr('number', {defaultValue: 0, key: 'storageID'}),
});
//create a couple of records
App.store.createRecord(App.Person, { ... } );
App.store.createRecord(App.Person, { ... } );
//try and find one record
App.store.find(App.Person, 0);
error thrown:
Uncaught Error: assertion failed: A data hash was loaded for a model of type App.Person but no primary key 'undefined' was provided. ember-latest.js:51
Ember.assert ember-latest.js:51
(anonymous function) ember-latest.js:131
DS.Store.Ember.Object.extend.load ember-data.js:1530
DS.LocalStorageAdapter.DS.Adapter.extend.find bookApp_1.js:111
DS.Store.Ember.Object.extend.findByClientId ember-data.js:1174
DS.Store.Ember.Object.extend.find ember-data.js:1140
findRecord webApplication.js:210
onclick
另请注意,这与之前发布的另一个问题类似: Ember Data: A data hash was loaded ... but no primary key 'undefined' was provided
尽管那里的答案似乎并不能真正解释发生了什么。