那么现在来回答一个大问题:有没有更好的方法可以从 Ember 外部访问路由器或控制器?最好使用上下文向其中任何一个发送事件。
是的。这听起来很适合 ember 仪表模块。让适当的控制器订阅 SignalR 事件,然后在您的应用处理实时通知时触发它们。
首先,向 ApplicationController 添加一个方法来处理更新。如果未在此处定义,则事件将冒泡到路由器。
App.ApplicationController = Ember.Controller.extend({
count: 0,
name: 'default',
signalrNotificationOccured: function(context) {
this.incrementProperty('count');
this.set('name', context.name);
}
});
接下来,通过订阅 signalr.notificationOccured 事件来设置您的 ApplicationController。使用 before 回调记录事件并将其有效负载发送到控制器。
App.ApplicationRoute = Ember.Route.extend({
setupController: function (controller, model) {
Ember.Instrumentation.subscribe("signalr.notificationOccured", {
before: function(name, timestamp, payload) {
console.log('Recieved ', name, ' at ' + timestamp + ' with payload: ', payload);
controller.send('signalrNotificationOccured', payload);
},
after: function() {}
});
}
});
然后从您的 SignalR 应用程序中,使用 Ember.Instrumentation.instrument 将有效负载发送到您的 ApplicationController,如下所示:
notificator.update = function (context) {
Ember.Instrumentation.instrument("signalr.notificationOccured", context);
});
我在此处发布了带有模拟 SignalR 通知的工作副本:http://jsbin.com/iyexuf/1/edit
有关检测模块的文档可以在 here 找到,也可以查看 specs 了解更多示例。