react-web-router-flux
Version:
adapter react native-router-flux for web
149 lines (127 loc) • 3.79 kB
JSX
/**
* 名称:适配react-native-router-flux 风格Actions
* 作者:Beven
* 日期:2016-11-14
* 描述:提供api方式进行页面路由跳转
*/
//>>引入依赖
import Scene from "./Scene";
import { browserHistory } from "react-router";
import Utils from "./utils";
let _router = null;
class Actions {
/**
* Actions构造函数
*/
constructor() {
this.create = this.create.bind(this);
this.iterate = this.iterate.bind(this);
this.pop = this.pop.bind(this);
this.refresh = this.refresh.bind(this);
this.focus = this.focus.bind(this);
}
/**
* 获取router对象
*/
get router(){
return _router;
}
/**
* 设置router对象
*/
set router(value){
_router = value;
}
/**
* 创建一组路由
* @param scenes {Scene} 根路由
*/
create(scenes) {
this.iterate(scenes);
return scenes;
}
/**
* 依次遍历所有创建的route,并且使用search进行递归创建scene对应api函数
* @param root {Scene} 根scene
*/
iterate(root) {
this.root = root;
this.assert(root.props, 'props should be defined for stack');
this.build(root);
this.search(root);
}
/**
* 递遍历指定scene路由
* @param scene {Scene} 路由
* @param parentKey {String} 当前路由的所有父路由组合名称
* @param parentUrl {String} 当前节点的所有父路由组合url
*/
search(scene, parentKey, parentUrl) {
let path = scene.props.path;
let children = scene.props.children;
if (!children || Object.prototype.toString.call(children) != "[object Array]") {
return;
}
parentUrl = parentUrl != null ? parentUrl + "/" + path : path;
parentKey = Utils.nameJoin(parentKey, parentKey != null ? scene.key : "");
for (let child of children) {
this.build(child, parentKey, parentUrl);
this.search(child, parentKey, parentUrl);
}
}
/**
* 生成scene对应的api函数
* @param scene {Scene} 路由
* @param parentKey {String} 当前路由的所有父路由组合名称
* @param parentUrl {String} 当前节点的所有父路由组合url
*/
build(scene, parentKey, parentUrl) {
let props = scene.props;
let key = scene.key;
let url = (parentUrl + "/" + scene.props.path).replace(/\/\//g, "/");
if (!this.isEmpty(key) && (props.component||props.getComponent)) {
key = Utils.nameJoin(key, parentKey);
this[key] = (props = {}) => {
return this.go(url, props);
}
}
}
current() {
if (global.location) {
return global.location.href;
}
}
/**
* 跳转到指定url
* @param url {String} url地址
* @param props {Object} 属性参数
*/
go(url, props = {}) {
let absUrl = Utils.param(url, props);
this.router.push(absUrl)
}
popTo(props = {}) {
}
pop(num) {
browserHistory.goBack();
}
jump(props = {}) {
browserHistory.go(props);
}
refresh(props = {}) {
if (global.location) {
return global.location.reload();
}
}
focus(props = {}) {
}
assert(v, message) {
if (this.isEmpty(v)) {
throw new Error(message);
}
}
isEmpty(v) {
return (v == null || v == undefined || v.toString().replace(/\s/g, '') == '');
}
}
export default new Actions();