Polymer dart: Data bind integer value to String attribute

后端 未结 2 1645
甜味超标
甜味超标 2020-12-22 00:53

I am trying to bind an integer to a String attribute. To say exactly, I am trying to bind a published integer variable to the value attribute of the text input element.

2条回答
  •  囚心锁ツ
    2020-12-22 01:09

    For Polymer 1.0.0 this worked fine for me

    Create a reusable behavior or just add the convertToNumeric() to your Polymer element:

    @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);
      }
    }
    

    Apply the behavior to your element:

    @PolymerRegister('app-element')
    class AppElement extends PolymerElement with InputConverterBehavior {
      AppElement.created() : super.created();
    
      @property int intValue;
    }
    

    In HTML of your element configure the input element:

    • bind value to your property: value="[[intValue]]" so the input element gets updated when the property changes
    • set up event notification to call the converter when the value changes on-input="convertToNumeric" notify-path="intValue" where intValue is the name of the property to update with the numeric value.
    
    
      
    
    

    An alternative approach

    Create a property as getter/setter:

      int _intValue;
      @property int get intValue => _intValue;
      @reflectable set intValue(value) => convertToInt(value, 'intValue');
    

    Create a behavior or add the function directly to your element

    @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);
      }
    }
    

    This way you can use the same markup as for text input fields

    
    

    or if you want to delay the update of the property until the input field is left

    
    

提交回复
热议问题