本文介绍了EmberJs 是否支持发布/订阅事件模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在评估将用于我们下一个项目的 JavaScript 框架.我真的很喜欢 Ember.但是在我们的应用程序中,我们需要来自数据层的事件机制来通知控制器层某些事情发生了变化.我知道可以在 Ember 中使用 obersevers,例如:

I'm recently evaluating a JavaScript framework to be used for our next project. I really like Ember. But in our application, we would need an eventing mechanism from the data layer to notify the controller layer that something has changed. I know one could use obersevers in Ember, for example,:

person.addObserver('fullName', function() {
  // deal with the change
});

但我更喜欢 Backbone.Events 中的更多内容,您可以订阅或发布事件,特别是:

But I like more in Backbone.Events that you could subscribe or publish an event, specifically:

var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

有人知道这在 EmberJS 中是否可行吗?

Anybody has an idea whether that's doable in EmberJS?

为了让您了解我的问题的一些背景知识,我们的应用程序是一个实时应用程序.因此,后端 RESTful 服务会时不时地向客户端(JavaScript 端)触发一个事件.我想要一个数据层,它封装了对后端 RESTful 服务的访问,但也保留了一个缓存.我希望 EmberJS.Data 可以帮助我解决这个问题(这是一个我想找到答案的单独问题).有了这个,我还希望在后端 RESTful 服务发生更改时更新缓存.一旦缓存对象更新,我希望控制器层得到通知.这基本上就是我在 JavaScript 端需要一些事件机制的原因.

To also give you some background about my question, our application is a real-time application. So from time to time, the backend RESTful service will fire an event to the client side (JavaScript side). I would like to have a data layer which encapsulate the access to the backend RESTful service, but also keeps a cache. I hope EmberJS.Data could help me with that (that's a separate question I want to find answers). With that, I would like also the cache to be updated whenever a change happened from the backend RESTful service. Once the cache object is updated, I would like the Controller layer to be notified. This is basically why I need some eventing mechanism in JavaScript side.

请注意,我不想使用观察者的原因是有时,事件可能意味着我必须执行一项操作,即加载消息,或指示语音呼叫即将到来.骨干方式对我来说似乎更自然.

Note that the reason I don't want to use the Observers is that sometimes, an event could mean I have to perform an action, i.e. load up a message, or indicate that a voice call is coming. The backbone way seems more natuarl to me.

谢谢

推荐答案

自提交 2326580/a> - 从 v0.9.6 开始可用 - 有一个 Ember.Evented Mixin,参见 http://jsfiddle.net/qJqzm/.

Since commit 2326580 - which is available since v0.9.6 - there is an Ember.Evented Mixin, see http://jsfiddle.net/qJqzm/.

var handler = Ember.Object.create({
    otherEvent: function() {
        console.log(arguments);
    }
});

var myObject = Ember.Object.create(Ember.Evented, {
    init: function() {
        this._super();
        this.on('alert', this, 'alert');
    },
    alert: function() {
        console.log(arguments);
    }
});
myObject.on('otherEvent', handler, 'otherEvent');

myObject.fire('alert', {
    eventObject: true
});
myObject.fire('otherEvent', {
    first: true
}, {
    second: true
});​

这篇关于EmberJs 是否支持发布/订阅事件模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 03:00