儘管我發現與Ember相關的大多數指南和教程都非常注重使用綁定和觀察者,但我還發現通過evented mixin有選擇地使用事件/訂閱者模式的功能非常強大。Emberjs Evented vs Observers
所以我忘乎所以之前,或開始偏袒另外一個模式,接受他們每個人都有自己的目的:
//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'));
}
});
,雖然噸他的例子有利於觀測,要麼可以使用模式,所以我的問題是: 哪些性能的優點和缺點(如果有的話)使用事件觸發的mixin和哪些性能的優點和缺點(如任何)使用觀察員?
感謝您的迴應,但我正在尋找開銷的差異,以便我可以爲任何模式可以用作問題的可行解決方案的情況做出更明智的決定。 –