问题
Let's say I have 2 independent set of controllers/models: Dog and Cat.
Now, whenever I create new Cat record (or delete existing one) I want Dog controller to observe for creation/deletion of the record and when new Cat record is created I want it to fire some action (for example console.log('Bark!')).
I don't want to send action from Cat controller to Dog controller directly in this case; I want Dog controller to be responsible for itself. In case it is possible, is there any way to tell from the Dog controllers point of view whether a record was created or deleted?
Any ideas how to do that?
回答1:
Using Ember Data
On the dog/cat controller you can create a reference to the cat/dog collection.
let's assume you're creating the dog controller
App.DogRoute = Em.Route.extend({
model: function(){
return this.store.find('dog');
},
setupController: function(controller, model){
this._super(controller,model);
controller.set('cats', this.store.all('cat'));
}
});
App.DogController = Em.ArrayController.extend({
catsChanged: function(){
}.observes('cats')
});
Additionally you could add an array observer and watch how the items are changing.
App.DogRoute = Em.Route.extend({
model: function(){
return this.store.find('dog');
},
setupController: function(controller, model){
this._super(controller,model);
var all = this.store.all('cat');
controller.set('cats', all);
all.addArrayObserver(controller);
}
});
App.DogController = Em.ArrayController.extend({
arrayWillChange: function(array, start, removeCount, addCount) {
console.log(arguments);
},
arrayDidChange: function(array, start, removeCount, addCount) {
console.log(arguments);
}
});
Using needs and watching the controller
App.CatsController = Em.ArrayController.extend({
needs: 'dog',
dogs: Em.computed.alias('controllers.dogs'),
dogsChanged: function(){
console.log('dogs changed');
}.observes('dogs.[]')
});
App.DogsController = Em.ArrayController.extend({
needs: 'cat',
cats: Em.computed.alias('controllers.cats'),
catsChanged: function(){
console.log('cats changed');
}.observes('cats.[]')
});
来源:https://stackoverflow.com/questions/24982638/ember-observe-for-creation-deletion-of-records