我创建了一个 Polymer 元素<bind-view>
,它根据当前路线创建和添加视图元素。该元素与route_hierarchical包一起使用。
有关更多详细信息,请参阅GitHub 上的BWU 聚合物路由。
路由配置看起来像
library bwu_polymer_routing_example.route_initializer;
import 'package:route_hierarchical/client.dart' as rt;
import 'package:bwu_polymer_routing/module.dart';
class RouteInitializer implements Function {
void call(rt.Router router, RouteViewFactory views) {
views.configure({
'usersList': routeCfg(
path: '/users',
view: 'user-list',
defaultRoute: true,
dontLeaveOnParamChanges: true,
enter: (route) => router.go('usersList', {})),
'user': routeCfg(
path: '/user/:userId',
view: 'user-element',
dontLeaveOnParamChanges: true,
mount: {
'articleList': routeCfg(
path: '/articles',
view: 'article-list',
defaultRoute: true,
dontLeaveOnParamChanges: true,
mount: {
'article': routeCfg(
path: '/article/:articleId',
view: 'article-element',
bindParameters: ['articleId', 'userId'],
dontLeaveOnParamChanges: true,
mount: {
'view': routeCfg(
path: '/view',
defaultRoute: true,
dontLeaveOnParamChanges: true),
'edit': routeCfg(
path: '/edit',
dontLeaveOnParamChanges: true)
})
})
})
});
}
}
包含元素,一个占位符,其中为当前路由配置的视图被添加<app-element>
。<bind-view>
视图可以嵌套。任何视图本身都可以包含一个<bind-view>
元素。这允许在没有太多样板的情况下创建分层视图组合。
<!DOCTYPE html>
<link rel='import' href='../../../../packages/polymer/polymer.html'>
<link rel='import' href='../../../../packages/bwu_polymer_routing/bind_view.html'>
<link rel='import' href='user_list.html'>
<link rel='import' href='user_element.html'>
<link rel='import' href='article_list.html'>
<link rel='import' href='article_element.html'>
<polymer-element name='app-element'>
<template>
<bind-view id='app-element'></bind-view>
</template>
<script type='application/dart' src='app_element.dart'></script>
</polymer-element>
该app_element.dart
文件包含路由器初始化代码
class AppModule extends Module {
AppModule() : super() {
install(new RoutingModule(usePushState: true));
bindByKey(ROUTE_INITIALIZER_FN_KEY, toValue: new RouteInitializer());
}
}
@CustomTag('app-element')
class AppElement extends PolymerElement with DiContext {
AppElement.created() : super.created();
@override
void attached() {
super.attached();
initDiContext(this, new ModuleInjector([new AppModule()]));
}
}
该包还包含一些辅助 mixin,用于向 Polymer 元素添加依赖注入 (DI)功能,例如DiContext
此处使用的 mixin。构造函数注入不能与 Polymer 一起使用,但事件是一个很好的替代品。
DiConsumer
mixin 允许使用这个简单的代码从 DI 请求一个实例
@CustomTag('article-list')
class ArticleList extends PolymerElement with DiConsumer {
@observable String userId;
@override
void attached() {
super.attached();
// The two lines below show how to request instances from DI
// but they are redundant here because
// route parameters are assigned to attributes of the view automatically
// when the view is created or when the values change
var di = inject(this, [RouteProvider /* add more types here as needed */]);
userId = (di[RouteProvider] as RouteProvider).parameters['userId'];
}
}