Ember — observe for creation/deletion of records

梦想的初衷 提交于 2019-12-20 05:39:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!