Hi,
I’m trying to figure out the simplest code to have a “dynamic alias” binding. Which in a perfect world could look like this:
App.DynamicInputComponent = Ember.Component.extend({
model: null,
attribute: null,
value: Em.computed.alias('model.'+this.get('atribute')) // Pseudo code
})
But right now, I have to resort to manually adding and removing observers. (code on jsbin)
App.DynamicInputComponent = Ember.Component.extend({
model: null,
attribute: null,
value: null,
// If the user changes the input box, push the change to the model
setValueToModel: function() {
this.get('model').set(this.get('attribute'), this.get('value'));
}.observes('value'),
setValueFromModel: function() {
var value = this.get('model').get(this.get('attribute'));
this.set('value', value);
},
// If the model changes, we need to propagate it to the input box
onPropertyChange: function() {
var model = this.get('model'),
_attr = this.get('oldAttribute'),
attr = this.get('attribute');
if (_attr) {
Ember.removeObserver(model, _attr, this, this.setValueFromModel);
}
Ember.addObserver(model, attr, this, this.setValueFromModel);
this.set('oldAttribute', attr);
this.setValueFromModel();
}.observes('attribute', 'model').on('init'),
});
This code does work, but I’m wondering if there a simpler, cleaner way to do this?