自 Ember Data 1.0 beta 1+ 以来,您不再在 Ember Data 中定义存储。
App.Store = DS.Store.extend({
revision: 13,
adapter: DS.SocketAdapter.create({})
});
只需使用这个就足够了:
App.ApplicationAdapter = DS.SocketAdapter;
该商店被传递到find
功能,如果你想要的话可以使用它。此外,您将超出范围内onmessage
,但这不是重点。
推荐
由于您的程序有两个部分,我建议使用依赖项注入创建适配器/传输层。这是一个粗略的草稿
运输
DS.SocketTransport = Ember.Object.extend({
uri: 'ws://localhost:8081/',
type: 'post',
ws: null,
store: null,
init: function(){
var uri = this.get('uri'),
type = this.get('type'),
store = this.get('store'),
ws = new WebSocket(uri);
// callbacks
ws.onopen = function() {
console.log('Connection established /all');
};
ws.onclone = function() {
console.log('Connection closed /' + 'all');
};
ws.onmessage = function(data) {
// if this is random post data, side load
store.load('post', data)
console.log(data);
};
this._super();
}
});
网络套接字适配器
App.MyWsAdapter = DS.RESTAdapter.extend({
transport: null,
find: function(store, type, id) {
var transport = this.get('transport');
// Do your thing here
return new Ember.RSVP.Promise(function(resolve, reject){
// use the transport here to send a message/get a message, containing
// the json for the type and id mentioned above then use
//resolve(json);
});
},
});
依赖注入
App.initializer({
name: "transport",
after:['store'],
initialize: function (container, application) {
var store = container.lookup('store:main'),
postTransport = application.PostTransport.create({store:store, type:'post'});
register("my:postTranspot", postTransport);
application.PostAdapter = App.MyWsAdapter.create({
transport: postTransport
});
}
});