使用avalon2 去构建一个 app-route

avalon2 的相关文章
https://segmentfault.com/blog/jslouvre

其实框架就是让你使用起来简单些

关于路由其实用一个轻便的框架就可以了

https://github.com/visionmedia/page.js

路由就是根据url后面的路径不同变换代码

前端路由由于其特殊性 最常见表述为这样的形式

#!/contact/me

然后我们直接上page.js使用代码

page.js 可以使你使用hashbang

现在我们开始写组件

avalon2 组件写法
https://segmentfault.com/a/1190000004949412

定义组件

avalon.component('ms-approute', {
    template: '
', defaults: { }, soleSlot: 'page' });

使用组件

js

 function deepFind(obj, path) {
    var paths = path.split('.')
            , current = obj
            , i;

    for (i = 0; i < paths.length; ++i) {
        if (current[paths[i]] == undefined) {
            return undefined;
        } else {
            current = current[paths[i]];
        }
    }
    return current;
}

var Approute = function (options) {
    var lastRoute = '';
    var lastRouteEle = {};
    var ele = {};

    function check(route) {
        var length = ele.target.children.length;
        for (var i = 0; i < length; i++) {
            (function (index) {
                var page = ele.target.children.item(index);
                if (page.dataset.route == route) {
                    lastRoute = route;
                    lastRouteEle = page;
                    page.setAttribute("selected", "");
                }
            })(i);
        }
    }

    function emit(newValue, oldValue) {
        lastRouteEle.removeAttribute("selected");
        check(newValue);
    }

    return {
        emit: emit,
        config: {
            onInit: function (a) {
                console.log("onInit!!");
            },
            onReady: function (a) {
                console.log("onReady!!");
                var self = this;
                ele = a;
                var route = deepFind(self, options.path);
                check(route);
            },
            onViewChange: function (a) {
                console.log("onViewChange!!");
            },
            onDispose: function (a) {
                console.log("onDispose!!")
            }
        }
    }
};

var approute = new Approute({
    path: "route"
});

var con = function () {
    return {
        $id: "test",
        route: "index",
        approuteconfig: approute.config
    }
};

var vm = avalon.define(con());

vm.$watch("route", function (newValue, oldValue) {
    approute.emit(newValue, oldValue);
});

你可能感兴趣的:(javascript)