【问题标题】:declared property being initialized multiple times when using data binding使用数据绑定时多次初始化声明的属性
【发布时间】:2016-02-25 00:11:03
【问题描述】:

聚合物 v1.2.3


我遇到了 Polymer 的问题,我不确定它是否是错误。

我有这个属性,我需要在ready 回调中对其执行某些操作后将其设置为 null,但是当我通过数据绑定初始化该属性时,该属性在我设置后重新初始化它为空。

举个例子:

proxy-elm.html

<dom-module id="proxy-elm">
  <template>
    <x-foo it="[[prox]]"></x-foo>
  </template>
  <script>
    Polymer({
      is: 'proxy-elm',
      properties: {
        prox: String
      }
    });
  </script>
</dom-module>

x-foo.html

<dom-module id="x-foo">
  <template>
    <div>...</div>
  </template>
  <script>
    Polymer({
      is: 'x-foo',
      properties: {
        it: String
      },
      ready: function () {
        //some processing stuff
        console.log(this.it);
        this.it = '';
        setTimeout(function () {
          console.log("later -- " + this.it);
        }.bind(this), 3000);
      }
    });
  </script>
</dom-module>

Main.html

<proxy-elm prox="hi"></proxy-elm>

控制台

=>hi
=>
=>later -- hi

只有在代理元素使用数据绑定时才会出现此问题。如果我将代理元素 it 设置为立即数,则控制台如下所示:

=>hi
=>
=> later -- 

这是期望的行为。


这是怎么回事?我要疯了!

【问题讨论】:

    标签: javascript html data-binding polymer web-component


    【解决方案1】:

    这确实令人困惑。然而,当我仔细阅读documentation 时,我注意到它只提到了local dom

    在元素的模板被标记并且所有元素在元素的本地 DOM 内都已配置(使用从父级绑定的值、反序列化属性或其他默认值)并准备就绪后调用它方法调用。

    所以保证你元素的本地子元素已经被初始化,但不一定是你元素的属性。 我注意到将代码包装在 async 中会有所帮助。

      ready: function () {
        //some processing stuff
        console.log(this.it);
        this.async(function(){
          this.it = '';
        });
        setTimeout(function () {
          console.log("later -- " + this.it);
        }.bind(this), 3000);
      }
    

    【讨论】:

    • 我想知道为什么它会完全可用。显然它在准备好之前就设置好了,但随后又设置了再次
    • 是的,我也发现这令人困惑。也许你可以在 Github 上询问,看看是否有开发者可以给出原因或解释当前的行为。
    【解决方案2】:

    这可能是由于初始化顺序(参见Documentation

    您可以尝试在您的代理中使用ready() 函数来根据需要设置x-foo 的值,如下所示:

    <dom-module id="proxy-elm">
      <template>
        <x-foo id="xFoo" it="[[prox]]"></x-foo>
      </template>
      <script>
        Polymer({
          is: 'proxy-elm',
          properties: {
            prox: String
          },
          ready: function () {
            this.$.xFoo.it = '';
          }
        });
      </script>
    </dom-module>
    

    并保留x-fooready()函数供您具体处理!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多