实现自定义路由

本文实现自定路由,主要是事件hashchange的使用,然后根据我们的业务需求封装。

首先实现一个router的类,并实例化。

function _router(config){
    this.config = config ? config : {};
}
_router.prototype = {
    event:function(str,callback){
        var events = str.split(‘ ‘);
        for (var i in events) window.addEventListener(events[i],callback,false);
    },
init: function() {
    this.event(‘load hashchange‘,this.refresh.bind(this));
    return this;
},
refresh: function() {
    this.currentUrl = location.hash.slice(1) || ‘/‘;
    this.config[this.currentUrl]();
},
route: function(path,callback){
    this.config[path] = callback || function(){};
}
}
function router (config){
    return new _router(config).init();
}

上边唯一需要注意的是,在使用addEventListener的时候,需要注意bind函数的使用,因为我是踩了坑,这才体会到$.proxy()。

上边使用的时候可以使用两种方法进行注册,但第二种是依赖第一种的。

方法一:

var Router = router({
    ‘/‘ : function(){content.style.backgroundColor = ‘white‘;},
    ‘/1‘: function(){content.style.backgroundColor = ‘blue‘;},
    ‘/2‘: function(){content.style.backgroundColor = ‘green‘;}
})

方法二:

Router.route(‘/3‘,function(){ content.style.backgroundColor = ‘yellow‘; })

完整代码:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <ul>
            <li><a href="#/1">/1: blue</a></li>
            <li><a href="#/2">/2: green</a></li>
            <li><a href="#/3">/3: yellow</a></li>
        </ul>
        <script>
        var content = document.querySelector(‘body‘);
        function _router(config){
            this.config = config ? config : {};
        }
        _router.prototype = {
            event:function(str,callback){
                var events = str.split(‘ ‘);
                for (var i in events) window.addEventListener(events[i],callback,false);
            },
            init: function() {
                this.event(‘load hashchange‘,this.refresh.bind(this));
                return this;
            },
            refresh: function() {
                this.currentUrl = location.hash.slice(1) || ‘/‘;
                this.config[this.currentUrl]();
            },
            route: function(path,callback){
                this.config[path] = callback || function(){};
            }
        }
        function router (config){
            return new _router(config).init();
        }
        var Router = router({
            ‘/‘ : function(){content.style.backgroundColor = ‘white‘;},
            ‘/1‘: function(){content.style.backgroundColor = ‘blue‘;},
            ‘/2‘: function(){content.style.backgroundColor = ‘green‘;}
        })
        Router.route(‘/3‘,function(){
            content.style.backgroundColor = ‘yellow‘;
        })

        </script>
    </body>
</html>
<script>
</script>
时间: 2024-12-18 01:57:05

实现自定义路由的相关文章

WPF自定义路由事件

一 概要 本文通过实例演示WPF自定义路由事件的使用,进而探讨了路由事件与普通的CLR事件的区别(注:"普通的CLR事件"这个说法可能不太专业,但是,我暂时也找不到什么更好的称呼,就这么着吧,呵呵.)(扩展阅读:例说.NET事件的使用). 二 实例演示与说明 1 新建DetailReportEventArgs类,该类派生自RoutedEventArgs类,RoutedEventArgs类包含与路由事件相关的状态信息和事件数据.DetailReportEventArgs类中定义了属性Ev

ASP.NET MVC 路由进阶(之二)--自定义路由约束

3.自定义路由约束 什么叫自定义路由约束呢?假如路由格式为archive/{year}/{month}/{day},其中year,month,day是有约束条件的,必须是数字,而且有一定范围. 这时候,我们就可以设置约束类,进行自定义路由约束了. 第一步: 我们先添加年份限制类 YearRouteConstraint.请看代码: using System; using System.Collections.Generic; using System.Linq; using System.Web;

WPF自定义路由事件(二)

WPF中的路由事件 as U know,和以前Windows消息事件区别不再多讲,这篇博文中,将首先回顾下WPF内置的路由事件的用法,然后在此基础上自定义一个路由事件. 1.WPF内置路由事件 WPF中的大多数事件都是路由事件,WPF有3中路由策略: 具体不多讲,单需要注意的是WPF路由事件是沿着VIsualTree传递的.VisualTree与LogicalTree的区别在于:LogicalTree的叶子节点是构成用户界面的控件(xaml紧密相关),而VisualTree要连控件中的细微结构也

YbSoftwareFactory 代码生成插件【二十四】:MVC中实现动态自定义路由

上一篇介绍了 公文流转系统 的实现,本篇介绍下MVC下动态自定义路由的实现. 在典型的CMS系统中,通常需要为某个栏目指定个友链地址,通过指定友链地址,该栏目的地址更人性化.方便记忆,也有利用于搜索引擎优化. 但在MVC中,通常需要在应用程序启动时注册路由规则,该路由规则又通常和控制器进行了关联,也就是某个地址通常情况下都是有对应的控制器进行处理的.但在MVC中如何做到自定义动态路由,以便能在运行时通过某个控制器处理一些运行时动态设定的Url地址呢? 方法当然是有的:    1.首先实现一个动态

自定义路由事件

自定义路由事件大体上可分为三个步骤: 1.声明并注册路由事件: 2.为路由事件添加CLR事件包装: 3.创建可以激发路由事件的方法. 主要的示例代码如下: public class TimeButton : Button { /// <summary> /// 声明并注册路由事件. /// </summary> public static readonly RoutedEvent ReportTimeEvent = EventManager.RegisterRoutedEvent(

Mvc-WebAPI特性路由(自定义路由)Demo

Demo由VS2017编写. 1.先建一个WebApi项目 2.WebApiConfig.cs需要注册特性路由,config.MapHttpAttributeRoutes(); 3.项目默认有2个Controller,我暂时不动默认的了,新建一个WebApiController:TestController 4.在TestController 类名上加上RoutePrefix特性,api前缀:在下面写一个测试的User类,后面会用到: 在TestController 写两个方法GetUser .

Web API配置自定义路由

默认访问Web API时,是无需指定method名.它会按照默认的路由来访问.如果你的Web API中出现有方法重载时,也许得配置自定义路由: 标记1为自定义路由,标记2为默认路由,需要把自定义路由排在前面.系统会先从自定义路由去匹配.

Mvc自定义路由让支持.html的格式

前言 在大多时候,我们都需要自定义路由,当我们设置为/list/1.html的时候,有的时候会出现以下异常. routes.MapRoute( "category", // 路由名称 "list/{cid}.html", new { controller = "Category", action = "Category" } ); 为什么会这样那,非常纠结,如果你把路由中的.html去掉访问,http://localhost:

WPF:自定义路由事件的实现

路由事件通过EventManager,RegisterRoutedEvent方法注册,通过AddHandler和RemoveHandler来关联和解除关联的事件处理函数:通过RaiseEvent方法来触发事件:通过传统的CLR事件来封装后供用户使用. 如何实现自定义路由事件,可以参考MSDN官网上的文档:如何:创建自定义路由事件 下面的这个demo参考自<葵花宝典--WPF自学手册>. 1.MainWindow.xaml 1 <Window x:Class="WpfApplic

Flutter自定义路由PageRouteBuilder

自定义路由翻转,渐变,左右滑动 方法如下: 首先继承 PageRouteBuilder ,重写方法 将MaterialPageRoute改为showSearch import 'package:flutter/material.dart'; class animation_route extends PageRouteBuilder { final Widget widget; animation_route(this.widget) : super( transitionDuration: c