自定义函数中聚合物属性未定义

Polymer undefined property in custom function

本文关键字:未定义 属性 聚合物 自定义函数      更新时间:2023-09-26

我使用聚合物 (v1.0),我想创建一个简单的元素,它可以显示我一些额外的内容取决于一个属性,它必须与多个值工作-又名一个简单的"开关"。

我写了这段代码。

...
    <span>{{for}}</span>
    <template is="dom-if" if="{{checkFor('alfa')}}">
        hi !!!
    </template>
</template>
<script>
    Polymer({
        is: "...",
        properties: {
            for: String,
            user: String,
            manager: {
                type: Boolean,
                notify: true
            }
        },
        attached: function() {
            this.textContent = 'Hello World, my user is ' + (this.user || 'nobody') + '.'n' +
                    'This user is ' + (this.manager ? '' : 'not') + ' a manager and he likes ' + this.for + '.';
        },

        checkFor: function (aaa) {
            // return aaa === this.for;
            this.textContent = 'Hello World, my user is ' + (this.user || 'nobody') + '.'n' +
                    'This user is ' + (this.manager ? '' : 'not') + ' a manager and he likes ' + this.for + '.';
        }
    });
</script>

我的函数checkFor用于检查我想要的值(例如'alfa')是否等于元素属性/属性for

但它根本不起作用,所以我尝试使用console.log()检查值。之后我发现变量aaa包含'alfa',变量this.for包含undefined

然后我复制了一些我发现使用元素属性的输出代码,它也不起作用。如果我在attached函数中运行相同的代码,它可以正常工作。

如何在自定义函数中使用元素属性?

第一次调用checkFor函数时,还没有定义this.for。您可以将for作为参数传递给函数,如文档中所述。

<template is="dom-if" if="{{checkFor('alfa', for)}}">