Alexander Hauer
Alexander Hauer

Reputation: 73

How to send an event to another views

As the answer on my previous question I learned that binding between two controller is kind of a bad design. I tried to solve it with event handling.

App.TestView = Ember.CollectionView.extend({     
 tagName:'tbody',
 contentBinding: 'this.controller.content',
 itemViewClass: Em.View.extend({
   templateName:'test',
   classNameBindings:['selected:selected'],
   selectedBinding: 'content.selected',
   click: function(event){
     var controller =  this.get('controller');
     this.resetSelection(); 
     this.content.set('selected',true);
     router = this.get('controller.target.router');  
     router.transitionTo('inc.index',this.content);
     // just sends it to the parentView
     controller.send('noHide',false);
   }
 })
});
App.MainMenuView = Em.View.extend({
 noHide: function(event){
 this.get('controller').set('isHidden',false);
 }
})

But now I don't know how to send events to other views or other routes that are not a parent view. I just want to toggle a hidden menu item when I click on a row of my table.

Upvotes: 1

Views: 880

Answers (2)

Thomas
Thomas

Reputation: 1321

You can use Ember.Instrumentation to call into any controller from anywhere else.

First subscribe to an event in setupController, you can choose whichever name you want for the event and call your desired function in the before handler. The payload is optional.

App.MyRoute = Ember.Route.extend({
  setupController: function (controller, model) {
    Ember.Instrumentation.subscribe("app.myEventName", {
      before: function (name, timestamp, payload) {
       controller.send('functionToCall', payload);
      },
      after: function () { }
    });
  }
});

When you want to call the function, you do the following

Ember.Instrumentation.instrument('app.myEventName', myPayload);

You can read more here http://emberjs.com/api/classes/Ember.Instrumentation.html

Upvotes: 1

Alexander Hauer
Alexander Hauer

Reputation: 73

Ok i figured it out myself. Here is the solution:

App.TableController = Em.ArrayController.extend({
 needs: ['mainMenu'],
 hidden:true,
 hiddenBinding: 'controllers.mainMenu.isHidden', 
  noHide: function(test){
    this.get('controllers.mainMenu').changeHidden(test);
 }
 })
App.MainMenuController= Em.Controller.extend({
 isHidden: true,
 changeHidden: function(test){
 this.set('isHidden',test)
 }
 });

The event is delegated to controller of the parentView. From there i got the link to my mainMenuController via 'needs' to call the changeHidden function.

Upvotes: 0

Related Questions