Skip to content

Instantly share code, notes, and snippets.

@SweeD
Created November 22, 2012 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SweeD/4130748 to your computer and use it in GitHub Desktop.
Save SweeD/4130748 to your computer and use it in GitHub Desktop.
EmberJS - Add a computed property via method
App.BaseMenuView = Ember.View.extend{
statesForActiveCheck: [],
init: function(){
this._super()
this.get('statesForActiveCheck').forEach(this.addActiveCheckMethod, this)
},
addActiveCheckMethod: function(statePart){
functionName = statePart.replace('.', '_').camelize() + 'Active'; // the function name for 'account.settings' should be 'accountSettingsActive'
this[functionName] = function(){
return this.isActiveState(statePath);
}.property('App.router.currentState')
// Also tried something like this and some other variants... all the same
//eval("this['" + functionName + "'] = function(){ return this.isActiveState('" + statePart + "')}.property('GleichklangWeb.router.currentState')")
},
accountEmailActive: function(){
return false
}.property('App.router.currentState'),
isActiveCheckMethod: function(){
// ....
}
}
App.ConcreteMenuView = App.BaseMenuView.extend{
statesForActiveCheck: ['account.settings'] // Should result in an computed property 'accountSettingsActive'
}
// When i call get() for the property 'accountSettingsActive' i get a ComputedProperty object
App.ConcreteMenuView.create().get('accountSettingsActive');
=> ComputedProperty
// But when i call get() for the initial defined property 'accountEmailActive' i get the right value back (false)
App.ConcreteMenuView.create().get('accountEmailActive');
=> false
// What am i doing wrong?
@SweeD
Copy link
Author

SweeD commented Nov 22, 2012

I wrote the original Code in Coffee and ported it to js for this gist. (in case there is a lack of return calls or something... ^^ )

@MKruschke
Copy link

//is it this what you mean

Ember.computed.not = function(dependentKey) {
return Ember.computed(dependentKey, function(key) {
return !get(this, dependentKey);
});
};

@SweeD
Copy link
Author

SweeD commented Nov 22, 2012

Ok, plusgut from the irc-channel helped me.

The solution is:

// .....

addActiveCheckMethod: function(statePart){
    functionName = statePart.replace('.', '_').camelize() + 'Active'; // the function name for 'account.settings' should be 'accountSettingsActive'
    Em.defineProperty(this, functionName, function(){
      return this.isActiveState(statePath);
    }.property('App.router.currentState'))
  },

// ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment