我已经整理了一个小示例,说明我目前是如何做到这一点的(希望我们很快就能看到一个更大的best practice个示例应用程序):
For the complete source code of this example see 100
主要应用
- app.html-包含主应用程序布局,实例化header和footer组件,并为视图创建容器.
- app.dart-处理导航事件并替换视图容器内的视图(见下文)
- app.css个
Web组件
页眉和页脚
- header.html-标题的Web组件
- footer.html-页脚的Web组件
视图
- contact.html-联系人视图的Web组件
- contact.dart-包含ContactsView类的DART文件
- products.html-产品视图的Web组件
- products.dart-包含ProductsView类的DART文件
在视图之间切换
达到instantiate Web组件的标准方法是在HTML中使用<x-foo></x-foo>
.
因为我们有不同的视图,所以我们必须实例化Dart代码中的Web组件.要做到这一点,我们必须手动调用Web组件生命周期方法.这不是直截了当的,将来可能会改进(参见Issue 93,其中也包含一些示例).
以下是如何切换视图(app.dart
的源代码):
import 'dart:html';
import 'package:web_ui/web_ui.dart';
import 'contact.dart';
import 'products.dart';
void main() {
// Add view navigation event handlers
query('#show-contact-button').onClick.listen(showContactView);
query('#show-products-button').onClick.listen(showProductView);
}
// Used to call lifecycle methods on the current view
ComponentItem lifecycleCaller;
/// Switches to contacts view
void showContactView(Event e) {
removeCurrentView();
ContactView contactView = new ContactView()
..host = new Element.html('<contact-view></contact-view>');
lifecycleCaller = new ComponentItem(contactView)..create();
query('#view-container').children.add(contactView.host);
lifecycleCaller.insert();
}
/// Switches to products view
void showProductView(Event e) {
removeCurrentView();
ProductsView productsView = new ProductsView()
..host = new Element.html('<products-view></products-view>');
lifecycleCaller = new ComponentItem(productsView);
lifecycleCaller.create();
query('#view-container').children.add(productsView.host);
lifecycleCaller.insert();
}
void removeCurrentView() {
query('#view-container').children.clear();
if (lifecycleCaller != null) {
// Call the lifecycle method in case the component needs to do some clean up
lifecycleCaller.remove();
}
}
下面是app.html
美元的来源:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Complex Web UI Application</title>
<link rel="stylesheet" href="app.css">
<!-- import the header and footer components -->
<link rel="components" href="header.html">
<link rel="components" href="footer.html">
<!-- import the view components -->
<link rel="components" href="contact.html">
<link rel="components" href="products.html">
</head>
<body>
<header-component></header-component>
<div id="view-container"></div>
<button id="show-contact-button">show contact view</button>
<button id="show-products-button">show products view</button>
<footer-component></footer-component>
<script type="application/dart" src="app.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
Note:我必须通过<link rel="components" href="contact.html">
导入视图组件,尽管我没有在HTML文件中直接引用它.