尽管我发现与 Ember 相关的大多数指南和教程都非常关注使用绑定和观察者,但我也发现通过事件混合有选择地使用事件/订阅者模式的强大功能。
所以在我得意忘形之前,或者开始偏爱一种模式而不是另一种模式之前,接受他们每个人都有自己的目的:
//This is Object to hold the ajax request (and fire the event)
App.serverAPI = Em.Object.createWithMixins(Em.Evented, {
responseData : '',
init: function(){
//Make the request on second from now
Em.run.later(this, function(){
this.request();
}, 1000);
this._super();
},
//The 'ajax' request function
request: function(myData){
var self = this;
$.ajax({
url:'/echo/json/',
type: 'POST',
data: {
json: JSON.stringify({"0":"Value One", "1": "Value Two", "2": "Value Three"}),
delay: 3
},
success: function(data){
console.log("Request successful ", data);
self.set('responseData', data);
self.trigger('responseSuccess', data);
}
})
}
});
现在一个视图将使用观察者更新:
//This View gets it's value updated by Observing a changed value in an other object
App.ObserverView = Em.View.extend({
templateName: "observer",
displayText: "Observer waiting...",
responseDataHandler: function(){
//Notice how we have to get the data here, where in a listener the data could be passed
var data = App.serverAPI.get('responseData');
//
//...Run functions on the data
//
this.set('displayText', data[0]+", "+data[1]+", "+data[2]);
console.log('Observer displayText', this.get('displayText'));
}.observes('App.serverAPI.responseData')
});
另一个视图将使用订阅者更新:
//This View gets it's value updated by subscribing to an event in an other object
App.SubscriberView = Em.View.extend({
templateName: "subscriber",
displayText: "Subscriber waiting...",
init: function(){
var self = this;
App.serverAPI.on('responseSuccess', function(data){
self.responseData(data);
})
this._super();
},
responseData: function(data){
//
//...Run functions on the data
//
this.set('displayText', data[0]+", "+data[1]+", "+data[2]);
console.log('Subscriber displayText', this.get('displayText'));
}
});
现在,虽然这个例子有利于观察者,但可以使用任何一种模式,所以我的问题是:使用事件混合的性能优势和劣势(如果有)是什么以及使用的性能优势和劣势(如果有)是什么观察者?