Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js - view isVisible (or any variable) binding to controller state

Tags:

ember.js

As read in the documentation, a controller should never call method or change properties on its associated view but instead the view should bind the state of its associated controller.

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 make it right?

Thanks in advance

like image 973
Fiftoine Avatar asked Feb 18 '23 05:02

Fiftoine


1 Answers

It should work this way:

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")
}

Needed changes to your code:

  1. I changed the isVisible property of your View from an observer to property. An observer fires (= function executes) everytime the watched property changes. So this is not what you need. But you want to define it as property so it can be accessed like this by Ember: view.get("isVisible"). Therefore i changed it to property.
  2. I changed the dependent key of your property. A controller is assigned to your view on the property controller. Therefore you need to prefix the desired property with controller to access it.
  3. As you see i also provided an even shorter version of this logic with the help of Ember.computed.alias, but i wanted to show you the more detailed solution first.
like image 79
mavilein Avatar answered May 07 '23 07:05

mavilein