对于聚合物1.0.0这个工作对我罚款
创建一个可重复使用的行为,或者只是添加convertToNumeric()
你聚合物元件:
@HtmlImport('app_element.html')
library app_element;
import 'dart:html' as dom;
import 'package:web_components/web_components.dart' show HtmlImport;
import 'package:polymer/polymer.dart';
@behavior
abstract class InputConverterBehavior implements PolymerBase {
@reflectable
void convertToInt(dom.Event e, _) {
final input = (e.target as dom.NumberInputElement);
double value = input.valueAsNumber;
int intValue =
value == value.isInfinite || value.isNaN ? null : value.toInt();
notifyPath(input.attributes['notify-path'], intValue);
}
}
将行为t Ø你的元素:
@PolymerRegister('app-element')
class AppElement extends PolymerElement with InputConverterBehavior {
AppElement.created() : super.created();
@property int intValue;
}
在你的元素的HTML配置输入元素:
- 绑定
value
你的财产:value="[[intValue]]"
所以当属性改变
- 设置事件input元素被更新通知在值更改时调用转换器
on-input="convertToNumeric" notify-path="intValue"
其中intValue
是使用数字值更新的属性的名称。
<!DOCTYPE html>
<dom-module id='app-element'>
<template>
<style>
input:invalid {
border: 3px solid red;
}
</style>
<input type="number" value="[[intValue]]"
on-input="convertToInt" notify-path="intValue">
<!-- a 2nd element just to demonstrate that 2-way-binding -->
<input type="number" value="[[intValue]]"
on-input="convertToInt" notify-path="intValue">
</template>
</dom-module>
另一种方法
创建一个财产的getter/setter:
int _intValue;
@property int get intValue => _intValue;
@reflectable set intValue(value) => convertToInt(value, 'intValue');
创建一个行为或直接添加的功能,你的元素
@behavior
abstract class InputConverterBehavior implements PolymerBase {
void convertToInt(value, String propertyPath) {
int result;
if (value == null) {
result = null;
} else if (value is String) {
double doubleValue = double.parse(value, (_) => double.NAN);
result =
doubleValue == doubleValue.isNaN ? null : doubleValue.toInt();
} else if (value is int) {
result = value;
} else if (value is double) {
result =
value == value.isInfinite || value.isNaN ? null : value.toInt();
}
set(propertyPath, result);
}
}
这样,您就可以使用相同的标记用于文本输入字段
<input type="number" value="{{intValue::input}}">
,或者如果你想拖延财产的更新,直到输入字段保留
<input type="number" value="{{intValue::change}}">