Polymer - 创建通用 属性 定义
Polymer - Creating a generic property definition
有没有办法在类型未知时定义 属性?
properties: {
value: {
type: Generic
}
}
执行此操作的最佳方法是什么?
我的问题来自一个可能是 String
或 Number
的值。我知道我可以 parseInt()
,但我随后需要检测是否有必要。此外,当 属性 是一个字符串时,该字符串可能是 value = '5'
,这使得有条件地应用 parseInt()
变得乏味。
您需要定义 Object
类型的 属性。
properties: {
value: Object
}
鉴于您的 属性 的可能值,解析是不可避免的,但可以很简单。例如,您可以使用带 String#replace
的正则表达式从输入中删除所有非数字字符,并将结果转换为 Number
:
Number(value.replace(/[^\d]+/g, ''))
HTMLImports.whenReady(() => {
Polymer({
is: 'x-foo',
properties: {
value: Object,
numberValue: {
computed: '_computeValue(value)'
}
},
_computeValue: function(value) {
// If the value is a string, remove all non-numeric
// characters and convert the result to a number.
return typeof value === 'string'
? Number(value.replace(/[^\d]+/g, ''))
: value;
}
});
});
<head>
<base href="https://polygit.org/polymer+1.7.1/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<x-foo value="100"></x-foo>
<x-foo value="value = '5'"></x-foo>
<x-foo value="foo 2 bar 4 baz 6 qux"></x-foo>
<dom-module id="x-foo">
<template>
<div>[[value]] ==> [[numberValue]]</div>
</template>
</dom-module>
</body>
有没有办法在类型未知时定义 属性?
properties: {
value: {
type: Generic
}
}
执行此操作的最佳方法是什么?
我的问题来自一个可能是 String
或 Number
的值。我知道我可以 parseInt()
,但我随后需要检测是否有必要。此外,当 属性 是一个字符串时,该字符串可能是 value = '5'
,这使得有条件地应用 parseInt()
变得乏味。
您需要定义 Object
类型的 属性。
properties: {
value: Object
}
鉴于您的 属性 的可能值,解析是不可避免的,但可以很简单。例如,您可以使用带 String#replace
的正则表达式从输入中删除所有非数字字符,并将结果转换为 Number
:
Number(value.replace(/[^\d]+/g, ''))
HTMLImports.whenReady(() => {
Polymer({
is: 'x-foo',
properties: {
value: Object,
numberValue: {
computed: '_computeValue(value)'
}
},
_computeValue: function(value) {
// If the value is a string, remove all non-numeric
// characters and convert the result to a number.
return typeof value === 'string'
? Number(value.replace(/[^\d]+/g, ''))
: value;
}
});
});
<head>
<base href="https://polygit.org/polymer+1.7.1/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<x-foo value="100"></x-foo>
<x-foo value="value = '5'"></x-foo>
<x-foo value="foo 2 bar 4 baz 6 qux"></x-foo>
<dom-module id="x-foo">
<template>
<div>[[value]] ==> [[numberValue]]</div>
</template>
</dom-module>
</body>