0

How is routing with components done with canjs?
I have following example

can.Component.extend({
    tag: "router",
    events: {
      "{can.route} id bla": function(route, event, id, bla) {
        console.log("route", id, bla);
      }
    }
  });

How can I match the specific route? For example page/2/foo.
The route is defined as

can.route(":page/:id/:bla", {page: "", id: "", bla: ""});
laser
  • 1,388
  • 13
  • 14
php--
  • 2,647
  • 4
  • 16
  • 18

1 Answers1

0

The trick to do routing in components is to not do routing in components. Instead, with something like

can.route(":page/:id", {page: "content", id: "index"});

You pass can.route as a state object. With a main view like:

<script id="main" type="text/mustache">
  <app-page page="state.page" page-id="state.id"></app-page>
</script>

rendered like can.view('main', { state: can.route }) your component then just checks those attributes:

can.Component.extend({
  tag: 'app-page',
  template: 'page',
  scope: {
    isBlog: function() {
      return this.attr('page') === 'blog';
    },

    isStatic: function() {
      return this.attr('page') === 'content';
    }
  }
});

With a view that initializes its child components:

<script id="page" type="text/mustache">
  {{#if isBlog}}
    <app-blog blog-id="pageId"></app-blog>
  {{/if}}
  {{#if isStatic}}
    <app-static page-id="pageId"></app-static>
  {{/if}}
</script>
Daff
  • 43,734
  • 9
  • 106
  • 120