Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameters to Dart Polymer element

The only solid example I could find for Dart Polymer doesn't use any parameters. How can I pass parameters to the template. Is it done through the constructor?

My specific example is that I have a card element with a title, and I want to pass the title of the card as a string to the element.

I have looked at Passing data to a Polymer element

but this is not exactly what I want to do. I want to pass data from within dart code.

like image 455
clocksmith Avatar asked Apr 10 '14 20:04

clocksmith


3 Answers

The constructor of elements is called from Polymer and there is no way to pass parameters.

You can as @Vloz wrote, assign values after the element was created or you can use binding as in the question you linked (Passing data to a Polymer element) using bindings.

like image 198
Günter Zöchbauer Avatar answered Sep 21 '22 03:09

Günter Zöchbauer


If you are creating a custom element you can use a factory constructor:

class MyElement extends HtmlElement {
  int _foo;
  factory MyElement(int foo) => new Element.tag('my-tag').._foo = foo;
  MyElement.created() {
     // Careful _foo has not been assigned yet.
  }
}

main() {
   document.register('my-tag', MyElement);
   var element = new MyElement(42);
}

I assume this also works for PolymerElements, but I haven't tried this myself.

like image 28
Greg Lowe Avatar answered Sep 19 '22 03:09

Greg Lowe


even though this is a bit old: You actually can pass parameters like this:

<my-custom-element booleanAttr valueAttr="test"></my-custom-element>

And your custom element should look something like:

@CustomTag('my-custom-element')
class MyCustomElement extends PolymerElement {
  ...
  @published bool booleanAttr;
  @published String valueAttr;
  ...
}

-- EDIT --

But as already pointed out this can be easily done for polymerelements with a factory:

import 'package:polymer/polymer.dart';
import 'dart:html';

@CustomTag('my-custom-element')
class MyCustomElement extends PolymerElement {
  String a;

  factory MyCustomElement.custom(String _a) {
    MyCustomElemente = new Element.tag('my-custom-element');
    e..a = _a
    // ...
    ..initialized();
    return e;
  }

  MyCustomElement.created() : super.created() {

  }

  void initialized() {
    print("initialized: " + a);
  }
}
like image 33
Robert Avatar answered Sep 22 '22 03:09

Robert