Ember に関連して私が見つけたガイドとチュートリアルのほとんどは、Binding と Observers の使用に重点を置いていますが、evented mixinを介して Event/Subscriber パターンを選択的に使用することにも大きな力があることを発見しました。
ですから、夢中になる前に、またはあるパターンを別のパターンよりも優先し始める前に、それぞれに独自の目的があることを受け入れます。
//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);
}
})
}
});
これで、オブザーバーを使用して 1 つのビューが更新されます。
//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'));
}
});
さて、この例はオブザーバーに有利ですが、どちらのパターンも使用できるので、私の質問は次のとおりです。オブザーバー?