Setting a bool published attribute with @published

2019-05-30 20:24发布

问题:

I have the following .dart component

@CustomTag('description-form')
class DescriptionForm extends PolymerElement {
  @observable Map<String, dynamic> datamap = {};
  @observable String description = '';

  @published
  String get label => readValue(#label);
  set label(String value) => writeValue(#label, value);

  @published
  bool get isVisible => readValue(#isVisible);
  set isVisible(bool value) => writeValue(#isVisible, value);

  DescriptionForm.created() : super.created();

  void publish() {
    datamap['description'] = description;
  }

  @override
  void attached() {
    super.attached();
    datamap['receiver'] = dataset['receiver'];
  }
}

To use the published attributes, I would do the following in a form

  <description-form
    label = 'Others'
    isVisible = false
    data-receiver = 'shared| description-form --> dynamic-chkbx'>
  </description-form>

While label is resolved, isVisible does not. What is the correct mechanism to set a bool that is published using @published?

回答1:

Typically, boolean attributes work based on whether they're present or not present. So if you set up the property in your class like so:

@PublishedProperty(reflect: true) bool isVisible = true;

Then you can use it in the HTML like this:

  <description-form
    label = 'Others'
    isVisible
    data-receiver = 'shared| description-form --> dynamic-chkbx'>
  </description-form>

When isVisible is present on the tag, it's true in the class, and changing the class's property to false removes the attribute on the tag (thanks to reflect: true).

Hope that helps!



回答2:

In response to @montyr75 s answer.

PublishedProperty(reflect: true) is necessary when you want the value of the field available in the DOM for example to be used in CSS selectors. If it is only used in code @published is fine. (still not entirely sure about this though).

If you want a boolean attribute that indicates true by the presence of the attribute and false by the a absence use a question mark like <description-form isVisible?="{{reference}}">

I tried a boolean attribute like you use it in your code and it just worked for me.

Another hint: If you want changes in your collections to take effect in the view you should make the collections observable @observable Map<String, dynamic> datamap = toObservable({});



回答3:

To simply answer your question:

The string from label will be correctly resolved. If you have a boolean published attribute isVisible just use <description-form></description-form> if you want isVisible to be false and <description-form isVisible></description-form> if you want it to be true.