Polymer.js 双向绑定到 textarea 值

Polymer.js two-way binding to textarea value

在 0.5 版本中很简单:

<polymer-element name="textarea-tpl" attributes="value placeholder">
    <template>
        <link rel="stylesheet" type="text/css" href="css/index.css">

        <textarea id="textarea" value="{{value}}" placeholder="{{placeholder}}"></textarea>
        <textarea id="hidden_textarea"></textarea>
    </template>
    <script>
        Polymer({
            ready: function() {
                var text = this.$.textarea;
                var hidden_text = this.$.hidden_textarea;

                text.onkeyup = function() {
                    hidden_text.value = text.value + "\n";
                    var height = hidden_text.scrollHeight;
                    text.style.height = height+'px';
                };
            }
        });
    </script>
</polymer-element>

在 1.0 版中,此绑定不起作用。只写作品而且很奇怪,只写一次。 v1.0 代码:

<dom-module id="chat-textarea">
    <template>
        <textarea id="textarea" value="{{value}}" placeholder="{{placeholder}}"></textarea>
        <textarea id="hidden_textarea"></textarea>
    </template>

    <script>
        Polymer({
            is: "chat-textarea",
            properties: {
                value: String,
                placeholder: String
            },

            set text(val) {
                this.$.textarea.value = val;
            },
            get text() {
                return this.$.textarea.value;
            },

            ready: function() {
                var text = this.$.textarea;
                var hidden_text = this.$.hidden_textarea;

                text.onkeyup = function() {
                    hidden_text.value = text.value + "\n";
                    var height = hidden_text.scrollHeight;
                    text.style.height = height+'px';
                };
            }
        });
    </script>
</dom-module>

现在我使用 set\get 文本,但它不是 属性 并且只能从 JS 获得。

在 iron-autogrow-textarea 中写道:因为 textarea 的值 属性 不可观察,所以您应该使用此元素的绑定值来代替命令式更新。 但是为什么在 0.5 中 textarea 的值是可见的?

要绑定到 Polymer 1.0 中的输入值,请在要绑定的变量后添加 ::input。

示例:

  <textarea value="{{taValue::input}}"></textarea>

这里是a working example on plnkr

iron-input 等元素使用bind-input 属性自动绑定变量。

two-way binding

的文档中有更多信息