mpm*_*mpm 2 backbone.js ractivejs
假设我在页面上有一个根Ractive,以及各种小部件来显示一个假设的骨干路由器何时导航到一个路由:
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 ... */})
Run Code Online (Sandbox Code Playgroud)
当路由是/ widget2时导航到/ widget1和widget2时会显示widget1,
根据当前路线交换小部件的最佳方法是什么,而不创建单独的根Ractive或隐藏/显示小部件?谢谢.
我之前建议的另一种解决方案,它允许以更动态的方式设置路由(即无需在模板中预先声明它们):
<nav>...</nav>
<!-- we have a single <route> component representing all possible routes -->
<route current='{{currentRoute}}'/>
Run Code Online (Sandbox Code Playgroud)
这可以像这样实现:
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
});
});
}
});
Run Code Online (Sandbox Code Playgroud)
然后,切换路线:
router.on( 'route', function ( route ) {
ractive.set( 'currentRoute', route );
});
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您需要做的就是在应用程序的某个位置注册所有可能的路线:
routes.widget1 = Ractive.extend({template:"<div>{{foo}}</div>"});
Run Code Online (Sandbox Code Playgroud)
...等等.如有必要,您可以通过检索引用与每个视图对象进行交互:
route = ractive.findComponent( 'route' );
route.view.on( 'someEvent', someEventHandler );
Run Code Online (Sandbox Code Playgroud)