Vijay Malik
Vijay Malik

Reputation: 117

concatenating string in the property being observed in the observer

I have a component in which I am observing a property from model and model is fed to controller in controller setup as controller property 'model'. Model has properties age, salary, rank. The property in component is to be entered by user.

The component will be called as:

{{ui-slider prop="age"}}

OR

{{ui-slider prop="salary"}}

This is not the complete component but it explains my problem.. The Component is :

App.UiSliderComponent = Ember.Component.extend({

prop:function(){
    return this.get('prop');
}.property('prop'),

modelPropertyObserver:function(){
    console.log("property is "+this.get('targetObject.model').get(this.get('prop'));
}.observes('targetObject.model.'+this.get('prop')),

didInsertElement:function(){
   console.log("Element inserted");
}

})

This is not working. When I observe property like
.observes('targetObject.model.age')
then it works fine.

But now it is showing
cori_component.js:29 Uncaught TypeError: this.get is not a function

I also tried .observes('targetObject.model.'+this.prop)
Though it doesn't show any error but the observer doesn't work.

How to concatenate the 'prop' property to the observer?
Or is there any way that I can concatenate the string inside component and then substitute it into observer.

Upvotes: 0

Views: 264

Answers (2)

Ember Freak
Ember Freak

Reputation: 12872

Innstead you can try,

{{ui-slider prop=model.age}}

and

modelPropertyObserver: Ember.observer('prop', function() {
    console.log("modelPropertyObserver");
})

I don't think the below one is acceptable.

.observes('targetObject.model.'+this.get('prop'))

Upvotes: 1

Pedro Rio
Pedro Rio

Reputation: 1444

You can try the following by overriding init and setting the property there (I've done this to have a dynamic computed property). I'm using Babel to have ES2015 features (like ...arguments and string interpolation )

init() {
this._super(...arguments);
this.set('value', Ember.computed(`model.${this.get('attribute')}`, function() {
  return this.get(`model.${this.get('attribute')}`);
}));
}

I assume by the documentation that you could replace Ember.computed with Ember.observer (and replace the corresponding method signature - snippet bellow copied from the documentation)

Ember.observer('value', function(sender, key, value, rev) {
// Executes whenever the "value" property changes
// See the addObserver method for more information about the callback arguments
}

Upvotes: 0

Related Questions