事件冒泡通过父控制器

时间:2013-10-02 01:54:46

标签: javascript ember.js

我有以下路线

App.Router.map(function() {
  this.resource('projects', {path: 'projects'}, function(){
      this.route('new', {path: 'new'});
      this.route('show', {path: ':project_id'});
      this.route('edit', {path: ':project_id/edit'});
  });  
});

我希望'ProjectsNewController','ProjectsShowController','ProjectsEditController'中的所有事件都冒泡到'ProjectsController'。

我怎样才能达到这个目标? JSBin:http://jsbin.com/ucanam/1284/edit

1 个答案:

答案 0 :(得分:15)

事件冒泡在ember中的工作方式是 not:

ChildController -> Controller -> ParentController

而是:

View -> Controller -> Route -> ApplicationRoute (optionally)

因此,如果某个事件从view触发,它将冒泡到controller并停在那里,如果controller从事件处理程序返回true那么它将继续冒泡到route。未在controllerroute中处理的事件将一直冒到ApplicationRoute

要实现您的目标,您应该使用needs API获取对ProjectsController的访问权限,并使用controller将事件/操作发送给.send(...)

例如:

App.ProjectsController = Ember.ArrayController.extend({
  actions:{
    newProject: function() {
      console.log("ProjectsController:newProject");
    }
  }
});

App.ProjectsNewController = Ember.ObjectController.extend({
  needs: ['projects'],
  actions:{
    newProject: function() {
      console.log("ProjectsNewController:newProject");
      // forward action to ProjectsController
      this.get('controllers.projects').send('newProject');
    }
  }
});

App.ProjectsEditController = Ember.ObjectController.extend({
  needs: ['projects'],
  actions:{
    newProject: function() {
      console.log("ProjectsEditController:newProject");
      // forward action to ProjectsController
      this.get('controllers.projects').send('newProject');
    }
  }
});

希望它有所帮助。