1

I have a main app component that uses login_form component, when the login form is submitted, I want to redirect the page to home, using the router.

/main_app/main_app.dart

@CustomTag('main-app')
class MainApp extends PolymerElement {
  @observable String route;

  final Router router = new Router();

  MainApp.created() : super.created();

  ready() {
    print('Main App: ready()');

    router.root
      ..addRoute(name: 'home', path: '/', enter: showHome, defaultRoute: true)
      ..addRoute(name: 'login', path: '/#!/login', enter: showLogin);

    router.listen();
  }

  void showHome(RouteEvent event) {
    print("Main App: showHome()");

    route = event.route.name;
  }

  void showLogin(RouteEvent event) {
    print("Main App: showLogin()");

    route = event.route.name;
  }
}

/login_form/login_form.dart

@CustomTag('login-form')
class LoginForm extends PolymerElement {
  @observable String username;
  @observable String password;

  LoginForm.created() : super.created();

  void submit(Event event, Object detail, Node sender) {
    // Form submit
    // Access router here
    // ie. router.go('home', {});
  }
}

I have found solutions such as using singleton like this

static final Router _sharedRouter = new Router();
static Router get sharedRouter => _router;

then

MainApp.sharedRouter.go('home', {}}

Is there a better way to do this?

Miguel Fermin
  • 380
  • 1
  • 3
  • 13

1 Answers1

1

Just create a binding from parent to child element:

Add a field route to your login-form

@CustomTag('login-form')
class LoginForm extends PolymerElement {
  ...
  String route;

  LoginForm.created() : super.created();

  void submit(Event event, Object detail, Node sender) {
    // Form submit
    // Access router here
    // ie. router.go('home', {});
  }
}

I assume you have placed your login-form somewhere inside the main-apps template.

<polymer-element name="main-app">
  <template>
    ...
    <login-form route="{{route}}"><login-form>
    ...
  </template>
</polymer-element>

This should update the route field in LoginForm every time the route field changes in MainApp.

If login-form isn't placed inside the main-apps template you can also use this approach https://stackoverflow.com/a/29864797/217408

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks, the login-form is placed inside the main-apps but nested, main-app component -> login-page-component -> login-form – Miguel Fermin May 26 '15 at 12:22
  • 1
    I see, then you would have to pass the `route` field to each child in the chain. The globals approach might be a better fit in this case. What you also can do is to fire an event on route change and interested components listen for this event and store the last received value passed with the event. – Günter Zöchbauer May 26 '15 at 12:23