Using computed property


#1

This is what I have in template:

{{check-box isChecked=hasPhoneForSecureAlerts visibleLabelLoc="_.t.settings_contact.label.phone" class=“checkbox-inline narrow” testId=“chk-phone”}}

This is what I have in controller for this property:

hasPhoneForSecureAlerts: Em.computed.bool(‘securePreferences.phoneLocalNumber’),

Let’s assume, that originally this property is set to true and check box is checked, If I uncheck check box, this property is set to false and actually does not correspond to state of securePreferences.phoneLocalNumber.

To set it to initial value, when we are leaving this screen without saving, I just use in resetController at corresponding route:

controller.set(‘hasPhoneForSecureAlerts’, controller.get(‘securePreferences.phoneLocalNumber’) !== null);

Is this code correct? It actually works fine, but I am finding anywhere in Emberjs documentation something like that. Thanks!


#2

better to put computed property to model than controller, if such property is not relative with UI


#3

This property is relative with UI - it is used by check box and just reflects that state of check box.


#4

I’m assuming you’re using Ember >= 2.0.0.

It is unclear to me if you want the values in sync or not. Let’s assume you do. If so, just use Ember.computed.alias instead of Ember.computed.bool.

Play with this JSBin to see how CPs react to changes and how it affects the model.


#5

Actually, what I want to do is completely opposite that using computes.alias. When I am changing a property, I don’t want also change another property that it depends on. This another property will be used to reset check box to original value if it is not saved. This property also on controller. It works very well for me but I am not sure if is a ember way.


#6

This is what actually I have: http://emberjs.jsbin.com/jiceqa/edit?html,js,output

emailAddress property of controller is loaded by the services and keeps original value of email address. When email is saved in database, the check box is checked. If we uncheck check box, null value for email address will be saved. When we are leaving the screen without saving, in resetController we just are setting hasPhoneForSecureAlerts back to state that corresponds to state of email address - true if there is email and false if there is no email. Not great design, but this is how it was originally done.