将输入字段绑定到对象上的int属性的正确方法是什么(例如,输入框更改并更新对象的int属性,导致绑定到同一属性的另一个元素进行更新)
示例代码如下;我可能在考虑采用这条路线的错误方法,但需要澄清一下。
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<link rel="import" href="components/calc.html">
<script type="application/dart">export 'package:polymer/init.dart';</script>
<script src="packages/browser/dart.js"></script>
</head>
<body>
<my-calc></my-calc>
</body>
</html>
<!-- calc.html -->
<polymer-element name="my-calc">
<template>
<label>Price</label>
<input value='{{ price }}'>
<label>Qty</label>
<input value='{{ qty }}'>
<label>Total</label>
<input value='{{ price * qty }}'>
</template>
<script type="application/dart" src="calc.dart"></script>
</polymer-element>
// calc.dart
import 'package:polymer/polymer.dart';
@CustomTag('my-calc')
class CalcElement extends PolymerElement {
@observable int price = 0;
@observable int qty = 0;
CalcElement.created() : super.created();
}
答案 0 :(得分:5)
您可以定义将String
转换为int
的{{3}}:
class StringToInt extends Transformer<String, int> {
String forward(int i) => '$i';
int reverse(String s) => int.parse(s);
}
然后您向asInteger
添加了一个属性PolymerElement
(您可以选择全局添加变换器,如two-way transformer of polymer expression中所述)。
// calc.dart
import 'package:polymer/polymer.dart';
@CustomTag('my-calc')
class CalcElement extends PolymerElement {
@observable int price = 0;
@observable int qty = 0;
final asInteger = new StringToInt();
CalcElement.created() : super.created();
}
最后使用这个变压器:
<!-- calc.html -->
<polymer-element name="my-calc">
<template>
<label>Price</label>
<input value='{{ price | asInteger }}'>
<label>Qty</label>
<input value='{{ qty | asInteger }}'>
....
</template>
<script type="application/dart" src="calc.dart"></script>
</polymer-element>
答案 1 :(得分:2)
你在这里走在正确的轨道上。唯一的问题是input元素的value
属性是一个字符串。一种方法是这样的:
<!-- calc.html -->
<polymer-element name="my-calc">
<template>
<label>Price</label>
<input value='{{ price }}'>
<label>Qty</label>
<input value='{{ qty }}'>
<label>Total</label>
<input value='{{ int.parse(price) * int.parse(qty) }}'>
</template>
<script type="application/dart" src="calc.dart"></script>
</polymer-element>
//calc.dart
import 'package:polymer/polymer.dart';
@CustomTag('my-calc')
class CalcElement extends PolymerElement {
@observable String price = "0";
@observable String qty = "0";
CalcElement.created() : super.created();
}
答案 2 :(得分:2)
我认为上面的答案是正确的方法,但我使用的是代替 Transformer :
class MyPolymerExpressions extends PolymerExpressions {
MyPolymerExpressions(): super(globals: {
'intToString': (int input) => '$input',
});
@override
prepareBinding(String path, name, node) => Polymer.prepareBinding(path, name, node, super.prepareBinding);
}
并在de calc.dart :
中添加此行@override PolymerExpressions syntax = new MyPolymerExpressions();
注意:要使用PolymerExpressions,您需要:
import 'package:polymer_expressions/polymer_expressions.dart';