Ember.js - viewing isVisible (or any variable) that binds to the state of the controller

As stated in the documentation, the controller should never call a method or change properties in the corresponding view, but instead, the view should bind the state of the controller associated with it.

Having this:

App.MyController = Ember.Controller.extend({ myViewVisible:false, toggleViewVisibitity:function(){ this.set('myViewVisible', !this.get('myViewVisible')); } } App.MyView = Ember.View.extend({ isVisible:function(){ return this.get('myViewVisible'); }.observes('myViewVisible') } 

When I call toggleViewVisibility from another controller, nothing happens in the view.

How can I do it right?

Thank you in advance

+4
source share
1 answer

It should work as follows:

 App.MyController = Ember.Controller.extend({ myViewVisible:false, toggleViewVisibitity:function(){ this.set('myViewVisible', !this.get('myViewVisible')); } } App.MyView = Ember.View.extend({ isVisible:function(){ return this.get('controller.myViewVisible'); }.property('controller.myViewVisible'), // even shorter version of the above isVisible : Ember.computed.alias("controller.myViewVisible") } 

Necessary changes in your code:

  • I changed the isVisible property of your view from observer to property. The observer starts (= function executes) every time the observed property changes. So this is not what you need. But you want to define it as a property so that it can be obtained, for example, using Ember: view.get ("isVisible"). So I changed it to a property.
  • I changed the dependent key of your property. A controller is assigned to your view in the property controller. Therefore, you need to prefix the required property with the controller to access it.
  • As you can see, I also provided an even shorter version of this logic using Ember.computed.alias , but first I want to show you a more detailed solution.
+8
source

All Articles