我对 Ember 相当陌生,多年来一直是一名铁杆 Backbone 爱好者,但我不知道如何处理我遇到的情况。
我正在使用Pusher和 Pusher Ember库来构建某种聊天应用程序。
它的工作方式是,一个人导航到用户帐户页面并创建一个新的“对话”。然后,一旦创建了该对话,我想订阅一个以该对话 ID 动态命名的推送 channel 。我需要在我的 Controller 上定义 Pusher 订阅。
这是我的路线(在 CoffeeScript 中)
App.ConversationShowRoute = Ember.Route.extend
model: (params) ->
@store.createRecord('conversation', user_id: params.user_id).save()
和我的 Controller :
App.ConversationShowController = Ember.ObjectController.extend
init: ->
subscriptions = []
subscriptions[@model.get('id')] = ['newMessage']
PUSHER_SUBSCRIPTIONS: subscriptions
不幸的是,模型此时尚未解析,因此我还不知道我的 @model.id
是什么,并且失败了。
对于处理这个问题的最佳方法有什么建议吗?
最佳答案
当我将 ember-pusher 添加到我的应用程序中时,我遇到了同样的问题。我采用的解决方案是在 App 命名空间中定义一个可以引用的变量。 (不理想,我稍后需要修复)
init: function () {
this.channelName = 'presence-document-' + App.documentId + '-channel';
this.PUSHER_SUBSCRIPTIONS[ this.channelName ] = [
'pusher:subscription_succeeded', 'pusher:member_added', 'pusher:member_removed',
'client-send-status', 'client-send-message'
];
this._super();
}
第二个更清晰的选项是尝试与用户 Controller 建立需求关系,但我不确定在初始化完成之前这是否可用。
App.ConversationShowController = Ember.ObjectController.extend({
needs: ['user'],
userId: Ember.computed.alias('controllers.user.id'),
init: function() {
this.PUSHER_SUBSCRIPTIONS[this.get('userId')] = ['newMessage'];
this._super(); // Maybe try putting this first if properties haven't resolved.
}
});
第三个选项是在初始化期间查找用户 Controller (单例)。
App.ConversationShowController = Ember.ObjectController.extend({
init: function() {
var userController = this.container.lookup('controller:user');
this.PUSHER_SUBSCRIPTIONS[userController.get('id')] = ['newMessage'];
this._super();
}
});
更新
由于您需要对话 ID,因此您可以观察模型何时发生变化,并按照 ember-pusher/bindings.js 的方式连接推送器。您不再需要覆盖controller.init,只需设置PUSHER_SUBSCRIPTIONS: {}
即可开始。
afterModelLoad: function() {
this.channelName = 'conversation-' + this.get('model.id');
this.PUSHER_SUBSCRIPTIONS[this.channelName] = ['newMessage'];
// From bindings.js init
var events = this.PUSHER_SUBSCRIPTIONS[this.channelName];
this.pusher.wire(this, this.channelName, events);
this.removeObserver('afterModelLoad'); /* If you only want to run once */
}.observes('model')
关于javascript - 模型在 Ember 中解析后,从路线触发 Controller 上的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26009324/