Stephen Cagle
Stephen Cagle

Reputation: 14534

How do I structure a "Controller" in Dart's web_ui?

I have the following code

xviewcontainer.html

<!DOCTYPE html>

<html>
  <head>
    <title>xviewcontainer</title>
    <link rel="components" href="xsearch.html">
    <link rel="components" href="xcard.html">
  </head>

  <body>
    <element name="x-view-container" constructor="ViewContainerComponent" extends="div">
      <template>
        <template instantiate="if view == 'SEARCH_VIEW'">
          <x-search></x-search>
        </template>
        <template instantiate="if view == 'CARD_VIEW'">
          <x-card></x-card>
        </template>
      </template>
    </element>
    <script type="application/dart" src="xviewcontainer.dart"></script>
    <!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

xviewcontainer.dart

import 'package:web_ui/web_ui.dart';

class ViewContainerComponent extends WebComponent {
  String view = 'SEARCH_VIEW';
}

I have the event handling code within some other currently rendered sub-component of x-search. How do I get a reference to the containing x-view-container instance? I wish to change the .view property so that x-view-container will render x-card instead of the currently rendered x-search. I would be specifically interested in how to do so from my event handlers relative position, how to do it in a absolute fashion, as well as how to do so in any other manner.

  void openCardView(){
    WHAT_DO_I_PUT_HERE.view = 'CARD_VIEW';
  }

Upvotes: 0

Views: 138

Answers (1)

Kai Sellgren
Kai Sellgren

Reputation: 30212

You can query for the element you have on the DOM with query() method. Simplest example is query('x-view-container'). Or assign a class or an id on it and query against that. Then access the xtag property to get the actual web component instance.

Here's an example:

import 'package:web_ui/watcher.dart' as watchers;

main() {
  // I'm assuming that the HTML tag is somewhere on the page.
  query('x-view-container').xtag.view = 'CARD_VIEW';

  watchers.dispatch(); // You may need to call this, or use @observable stuff.
}

Upvotes: 2

Related Questions