【问题标题】:Data Binding between Polymer Templatizer instance and hostPolymer Templatizer 实例和主机之间的数据绑定
【发布时间】:2017-05-26 00:59:32
【问题描述】:

我正在尝试使用 Polymer 模板器来创建模板的单个实例,将其附加到 div 中并让数据绑定在主机和此实例之间工作,但很难让它工作。

我试过的最简单的例子:

HTML

<dom-module id="test-app">
  <paper-input label="host" value="{{test}}"></paper-input>
  <template id="template">
    <paper-input label="instance" value="{{test}}"></paper-input>
  </template>
  <div id="placehere"></div>
</dom-module>

JS

Polymer({
  is: "test-app",
  behaviors: [Polymer.Templatizer],
  properties: {
    test: {
      type: String,
      value: 'hello',
      notify: true,
    },
  },

  ready: function() { 
    this.templatize(this.$.template);
    var clone = this.stamp({test: this.test}); 
    Polymer.dom(this.$.placehere).appendChild(clone.root);
  },
});

上面的想法是创建模板的实例,将其放入“placehere”,并使两个输入文本框保持同步。

当页面加载时,实例创建成功,两个文本框中的值都是“hello”,但是改变任何一个输入框都不起作用。

聚合物页面上的文档似乎有点轻量级: https://www.polymer-project.org/1.0/docs/api/Polymer.Templatizer 但它提到了_forwardParentProp 和_forwardParentPath 的使用。我应该如何在我的情况下实施它们?

【问题讨论】:

    标签: javascript html data-binding polymer


    【解决方案1】:

    正如您已经知道的那样,您需要实现一些 Templatizer 的方法。特别是 _forwardParentProp_forwardParentPath 方法。

    但在开始之前,我还必须指出自定义元素定义中的另一个错误。在您的 dom-module 元素中,您可以在没有模板的情况下定义元素的内容。必须将所有内容包装在 template 元素中。您的自定义元素的固定版本如下所示:

    <dom-module id="test-app">
      <template>
        <paper-input label="host" value="{{test}}"></paper-input>
        <template id="template">
          <paper-input label="instance" value="{{test}}"></paper-input>
        </template>
        <div id="placehere"></div>
      </template>
    </dom-module>
    

    至于Templatizer方法的实现,首先需要存储被标记的实例。之后,这两种需要实现的方法或多或少都是简单的单行代码。

    这是自定义元素的完整 JavaScript 部分:

    Polymer({
      is: "test-app",
      behaviors: [Polymer.Templatizer],
      properties: {
        test: {
          type: String,
          value: 'hello',
          notify: true,
        },
      },
    
      ready: function() { 
        this.templatize(this.$.template);
        var clone = this.stamp({test: this.test});
        this.stamped = clone.root.querySelector('*'); // This line is new
        Polymer.dom(this.$.placehere).appendChild(clone.root);
      },
    
      // This method is new
      _forwardParentProp: function(prop, value) {
        if (this.stamped) {
            this.stamped._templateInstance[prop] = value;
        }
      },
    
      // This method is new
      _forwardParentPath: function(path, value) {
        if (this.stamped) {
            this.stamped._templateInstance.notifyPath(path, value, true);
        }
      },
    });
    

    这是一个有效的 JSBin 演示:http://jsbin.com/saketemehi/1/edit?html,js,output

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2018-07-02
      相关资源
      最近更新 更多