Wednesday, April 11, 2012

Proper way to redirect binding in Ember.js

I've read the Ember.js documentation + samples, and nested views with bindings are confusing me a little bit.



I have the following abbreviated HTML (working fine):



{{#view App.outerArea}}
{{#view innerArea}}
{{view Ember.TextField valueBinding="parentView.parentView.bound.username"}}
{{/view}}
{{/view}}


...and JavaScript (also working fine):



App = Ember.Application.create();
App.outerArea = Ember.View.extend({
bound : {
username:'test',
},
innerArea: Ember.View.extend({}),
});


(If I remove innerArea from the HTML I can remove 'parentView.parentView.' entirely.)



To clean this up I've tried:



...
{{view Ember.TextField valueBinding="bound.username"}}
...
innerArea: Ember.View.extend({
bound: function() {
return App.outerArea.bound;
}
})


And tried:



{{view Ember.TextField valueBinding="getPath(bound.username)"}} // with above bound: function().


And some other combinations, but they don't work at all.



Is there a more elegant way to reference 'parentView.parentView.bound.username' from the TextField valueBinding? Is there more than one approach to this? What are the best design patterns for this sort of thing?



Thank you!





1 comment:

  1. Make sure to use get/getPath in your JS. Also your bound property became a computed property when you altered it and so should be something like :

    innerArea: Ember.View.extend({
    bound: function() {
    return App.getPath('outerArea.bound');
    }.property('outerArea.bound')
    })

    probably better removing the absolute paths :

    innerArea: Ember.View.extend({
    bound: function() {
    return this.getPath('parentView.bound');
    }.property('parentView.bound')
    })

    Disclaimer: untested - do some more reading of the emberjs docs around paths and computed properties.

    ReplyDelete