Best way to get model associated with a core-item element?

Issue

Consider this Polymer fragment:

<core-menu on-core-activate="{{selectUser}}">
  <template repeat="{{user in users}}">
    <core-item label="{{user.name}}"></core-item>
  </template>
</core-menu>

When a user clicks on a core-item element and triggers selectUser, how do I determine what user is associated with the activated core-item? I’d like to get an instance to the actual object, and not some stringified identifier that I would use to look up the object.

Solution

Polymer >= 1.0.0

@reflectable
void someClickHandler(dom.Event event, [_]) {
  // for native events (like on-click)
  var model = new DomRepeatModel.fromEvent(event);
  // or for custom events (like on-tap, works also for native events)
  var model = new DomRepeatModel.fromEvent(convertToJs(event));
  var value = model.jsElement['items']; 
  // or 
  var value = model.jsElement[$['mylist'].attributes['as']];
  // if you used the `as="somename"` 
  // in your <core-list> or <template is="dom-repeat">
}

There is an open issue related to custom events: https://github.com/dart-lang/polymer-dart/issues/624

Polymer <= 0.16.0

In the click handler

import 'package:template_binding/template_binding.dart' as tb;

...

void onClick(MouseEvent e) {
  tb.TemplateInstance ti = tb.nodeBind(e.target).templateInstance; 
  var value = ti.model.value as Inner;
}

see In Polymer.js children of a template have a reference to the template, how can this be done in Polymer.dart for more details.

Answered By – Günter Zöchbauer

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.