Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

ember.js - Ember TextField valueBinding with dynamic property

I'm trying to write a generic view that handles custom fields in my app, but I'm having a hard time getting this to work. Here's the scenario - I have a fieldDef object which defines the custom fields, and a valueObject which has an array, customFields, which has the values. What I'm trying to do is something like this:

{{view Ember.TextField valueBinding="valueObject.customFields.[fieldDef.name]"}}

Obviously that doesn't work because it treats fieldDef.name as a literal. I've tried overriding the TextField class, but can't seem to get it to bind.

Any suggestions on how to accomplish this?

Thanks, Scott

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ember can't bind to an array index, so you'll have to work around it. One solution is to limit yourself to a one-way binding, where your textfield updates the values hash. If you're planning to submit the form after the user presses a button, this should do the trick.

Define an array of field ids in your controller and a hash for their values to go in.

App.ApplicationController = Ember.Controller.extend({
  fieldIds: ['name', 'email', 'whatever'],
  fieldValues: {} // {name: 'user', email: 'user@...', ...}
});

Now extend Ember.TextField to update your values hash when a text field changes. You'll need to pass each instance a fieldId and a reference to the values hash from your controller.

App.TextField = Ember.TextField.extend({
  fieldId: null,
  values: null,

  valueChange: function() {
      var fieldId = this.get('fieldId');
      var values = this.get('values');
      if (values && fieldId) values[fieldId] = this.get('value');
  }.observes('value')
});

The template is simple.

{{#each fieldId in fieldIds}}
  <label>{{fieldId}}</label>
  {{view App.TextField fieldIdBinding="fieldId" valuesBinding="fieldValues"}}
  <br/>
{{/each}}

Here it is fleshed out in a jsfiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...