Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ractive ,Components and routing

Let's say I have one root Ractive on the page,and various widgest to show when an hypothetic backbone router navigate to a route :

var widget1=Ractive.extend({template:"<div>{{foo}}</div>"});
var widget2=Ractive.extend({template:"<div>{{bar}}</div>"});

var view=new Ractive({
   template:"<nav></nav><widget />",
   components:{widget:widget1}
});

var Router=Backbone.Router.extend({/* the code ... */})

so widget1 would be shown when I navigate to /widget1 and widget2 when the route is /widget2,

What would be the best way to swap widgets depending on the current route without creating seperate root Ractives or hiding/showing widgets? thanks.

like image 673
mpm Avatar asked Dec 10 '25 09:12

mpm


1 Answers

An alternative solution to my previous suggestion, which allows routes to be set in a more dynamic fashion (i.e. without having to declare them in a template up-front):

<nav>...</nav>

<!-- we have a single <route> component representing all possible routes -->
<route current='{{currentRoute}}'/>

This could be implemented like so:

Ractive.components.route = Ractive.extend({
  template: '<div class="container"></div>',
  init: function () {
    this.container = this.find( '.container' );

    this.observe( 'current', function ( currentRoute ) {
      var View = routes[ currentRoute ];

      if ( this.view ) {
        this.view.teardown();
      }

      this.view = new View({
        el: this.container
      });
    });
  }
});

Then, to switch routes:

router.on( 'route', function ( route ) {
  ractive.set( 'currentRoute', route );
});

With this approach all you'd need to do is register all the possible routes at some point in your app:

routes.widget1 = Ractive.extend({template:"<div>{{foo}}</div>"});

...and so on. If necessary you could interact with each view object by retrieving a reference:

route = ractive.findComponent( 'route' );
route.view.on( 'someEvent', someEventHandler );
like image 177
Rich Harris Avatar answered Dec 12 '25 02:12

Rich Harris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!