【问题标题】:Polymer Lifecycle: Why are properties not yet loaded from DOM attributes at 'Attached' callback?Polymer Lifecycle:为什么在“附加”回调中尚未从 DOM 属性加载属性?
【发布时间】:2015-11-14 13:59:15
【问题描述】:

我很难理解polymer element lifecycles

假设我有一个具有单个属性 fooBar 的自定义元素。并假设我将fooBar 设置为属性上的一个属性,如下所示。

<custom-element foo-bar="text"></custom-element>

现在假设我想在元素生命周期创建期间以编程方式使用fooBar 作为属性。就像这样。

Polymer({
    is: "custom-element",
    properties: {
        fooBar: {type: String}
    },
    ready: function(){
        console.log(this.fooBar)
    }, 
    attached: function(){
        console.log(this.fooBar)
    }
})

据我所知,直到调用readyattached 之后,才从DOM 属性fooBar 加载元素属性fooBar。这是真的even when I call async from inside the ready and attached callbacks

谁能解释 (1) 元素属性在生命周期的哪个位置从 DOM 属性导入,以及 (2) 如何以编程方式访问这些属性以对元素进行一些设置工作?

【问题讨论】:

    标签: javascript polymer polymer-1.0 web-component google-web-component


    【解决方案1】:

    如果您阅读过自定义元素规范,在元素的生命周期中有一个名为 attributeChangedCallback(name, oldVal, newVal) 的回调,它在 Polymer 中方便地重命名为 attributeChanged(type, name)。但是,这不是监听属性的首选方式,而是将观察者附加到该属性,在本例中为 fooBar

    这是一个 jsbin 示例。您可以看到fooBarChangedattachedready 之前首先被调用。

    http://jsbin.com/gibopu/edit?html,console,output

    【讨论】:

    • 是的,我知道那个选项,但它看起来很老套,特别是因为我不想破坏每次更改的回调 - 只是第一个用于设置目的。
    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多