Ember.js: TextField with dynamic binding

故事扮演 提交于 2019-12-02 09:32:00

问题


I want to bind a TextField to a property which is specified by a string variable (see the edit for a better explanation), as in this question. Unfortunately the answer that was given there does not work anymore. They use the following view there:

App.AutoTextField = Ember.ContainerView.extend({
    type: null,
    name: null,

    init: function() {
        this._super();
        this.createChildView();
    },
    createChildView: function() {
         this.set('currentView', Ember.TextField.create({
                    valueBinding: 'controller.' + this.get('name'),
                    type: this.get('type')
                }));   
    }.observes('name', 'type')
});

The best I could get until now was replacing the valueBinding with the path _parentView.context.. If I do this the text fields get rendered and they contain the correct value. If I edit them the rest of the application doesn't get updated though.

How would you solve this in the current version of Ember?

Edit: A better explanation of what I want to do is given in the linked question. I have an object (say object) and a string (key) in the current context. I want a text field that can show and render the value of object[key].


回答1:


After many failed attempts I found a pretty simple solution.

Add the helper

Ember.Handlebars.helper('dataTextField', function (data, key, options) {
    options.hash.valueBinding = 'data.' + key;

    return Ember.Handlebars.helpers.input.apply(this, [options]);
});

and then call

{{dataTextField data key}}

This will render a text field that shows and changes the value of data[key] and it even supports all the optional arguments the normal input helper can understand.




回答2:


You can bind input values with dynamic keys(variables) of objects with help of mut helper now.

https://guides.emberjs.com/v2.6.0/templates/input-helpers/#toc_binding-dynamic-attribute

We can bind key in input helper like this,

{{input value=(mut (get Object key))}}



回答3:


It's a little unclear what your use case is from your question but assuming your just trying to get a basic binding on the text field working then the easiest way to bind a value is to use the input helper:

In your template you would use:

{{input type="text" value=inputTextValue}}

where inputTextValue is the property you are binding the value to. Then in your controller you could access the inputTextValue property to either get the value typed in by the user, or to set the value displayed to the user.

Here's a working fiddle:

http://jsfiddle.net/NQKvy/940/

You can find more information on the input helper in the Ember docs here:

http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_input

Hope that helps.



来源:https://stackoverflow.com/questions/23308702/ember-js-textfield-with-dynamic-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!