我的后端正在向我发送这个 JSON(示例):
{
id: 0,
list: [
{username:'user_1', name:'Name1', surname:'Surname1', user:0},
{username:'user_2', name:'Name2', surname:'Surname2', user:0},
]
}
我有必要App.WUser
使用这种类型的 JSON 引导我的表。数据来自 WebSocket。我的 Ember.js 架构定义如下:
App.WUser = DS.Model.extend({
list: DS.hasMany('App.User')
});
App.User = DS.Model.extend({
username: DS.attr('string'), // primary key
name: DS.attr('string'),
surname: DS.attr('string'),
user: DS.belongsTo('App.WUser')
});
我为 WebSocket 实现编写了我的自定义适配器。请注意,App.WebSocketConnection
Mixin 包含连接处理程序(请参见最后一个片段)。
DS.SocketAdapter = DS.RESTAdapter.extend(App.WebSocketConnection, {
socket: undefined,
init: function() {
socket = this.getSocket(); // activate WS connection (see Mixin)
this._super();
},
find: function (store, type, id) {
// empty block
},
findAll: function (store, type) {
// empty block
},
createRecord: function(store, type, record) {
// code not relevant
}
});
DS.SocketAdapter.map('App.User', {
primaryKey: 'username'
});
DS.SocketAdapter.map('App.WUser', {
list: {embedded: 'always'}
});
我的商店
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.SocketAdapter.create({})
});
我的混音:
App.WebSocketHandler = Ember.Object.extend({
uri: 'ws://localhost:8080/App/atmosphere/chat/all',
ws: ,
init: function() {
this.ws = new WebSocket(this.uri));
// callbacks
this.ws.onopen = function() {
console.log('Connection established /all');
};
this.ws.onclone = function() {
console.log('Connection closed /' + 'all');
};
this.ws.onmessage = function(data) {
alert('New JSON message from server /all ' + data); // <---- ???
};
this._super();
},
send: function(data) {
// not relevant method... this method simply send a message to the server
/*
var some = ...
this.ws.send( JSON.stringify( some ) );
*/
}
});
在谷歌上搜索,我开始编写这段代码:
var JSONfromWebSocket = {
id: 0,
list: [
{username:'user_1', name:'Name1', surname:'Surname1', user:0},
{username:'user_2', name:'Name2', surname:'Surname2', user:0},
]
};
var store = DS.get('defaultStore');
store.loadMany(App.WUser, [0], JSONfromWebSocket); // should I specify the [0] id?
(?) this.didCreateRecords(store, App.WUser, records(?), undefined); // is it a neccessary line?
问题:
- 我把我的代码放在哪里?
- 我的代码正确吗?这是引导数据的正确方法吗?
- custum primaryKey 的使用是否正确?
- 考虑到我的表的自定义 ID
App.User
;对 loadMany() 函数的调用是否正确? - 请注意,JSON 来自onmessage回调(参见第 1 行
`// <---- ???
)。如何调用适配器继承的函数之一(以及哪个函数)(iecreateRecords),并将 JSON 数据传递给它?
我有点困惑,但我希望我是在正确的方式......我的问题是粘合我的代码片段!
谢谢耐心!
马蒂亚