Reuben Posthuma
Reuben Posthuma

Reputation: 159

Ember binding to array element

I'm trying to set up an ember binding between a controller and a model. The controller is part of an array (see question Ember.js views (unlimited number)), and so I'm trying to set up the binding to an element in a the model (an ArrayProxy) with the same index as the index of the controller itself.

The binding works if I link it to a non-indexed element of the ArrayProxy, but not if I try set an element of the array. So, if I set up the binding like:

answerBinding: 'App.SurveyData.test'

and in App.SurveyData set 'test' to be a string, say "StackOverlow", the two way binding is set up correctly. If I set up a binding like

answerBinding: 'App.SurveyData.content'

where content is an array, I can view in the console that 'answer' has a value of 'Array[2]' and each element equals 'Test object' as expected

When I try to set up the answerBinding as

answerBinding: 'App.SurveyData.content[0]'

which is trying to link answer to the first element in SurveyData as required, I can view in the console that 'answer' has a value of undefined.

Code is at http://jsfiddle.net/reubenposthuma/dyLGG/1/

Any thoughts would be appreciated

Upvotes: 2

Views: 2295

Answers (2)

Reuben Posthuma
Reuben Posthuma

Reputation: 159

As Mars said, bindings cannot accept indices of arrays, so I created a workaround. It is one way, although it could be modified to have an observer on the array itself for two way bindings. For my purposes (taking data from a survey and putting it in a answer array) one way bindings work perfectly.

answerObserver: function() {
  App.SurveyData.content[this.id-1] = this.answer;
}.observes('answer'),

whenever the data (in this case a textbox) changes, the changes will be copied into the index of the array.

Upvotes: 0

Mars
Mars

Reputation: 1528

Ember's bindings only work for properties. Specific indexes of Array cannot be bound, unless you do so via a computed property, like:

answerBinding: 'App.SurveyData.firstItem'

...and in App.SurveyData defined the computed property:

firstItem: function() { return this.objectAt(0); }.property('content')

Think about it this way: the array index is an argument to the [] function (not literally, but for the sake of this explanation.) Bindings cannot except arguments; they are purely a static path to a property to bind.

Upvotes: 2

Related Questions