From e781db308b6b412466ed0d3cd0e47e6947cbda19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=9F=E9=85=8C=20=E9=B5=AC=E5=85=84?= Date: Wed, 22 Oct 2014 18:48:34 +0800 Subject: [PATCH] Router emits event --- net/Router.js | 18 ++++++++++++++---- net/WebFrame.js | 9 +++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/net/Router.js b/net/Router.js index c15b6b0..872ba01 100644 --- a/net/Router.js +++ b/net/Router.js @@ -1,5 +1,9 @@ var Dragonfly = global.Dragonfly; -var FatalError = require( '../errors/FatalError.js' ); + +var util = require( "util" ) + , events = require( "events" ) + , FatalError = require( '../errors/FatalError.js' ) +; var MaxRedirect = 10; @@ -19,6 +23,8 @@ var RelayPoint = function( uri, internal ) var Router = function( http ) { + events.EventEmitter.call( this ); + this.HTTP = http; this.routes = {}; this.routable = true; @@ -27,11 +33,13 @@ var Router = function( http ) // Changed when routing this.inputs = []; this.routeObj = {}; - this.reroute = false; + this.reRoute = false; this.relaying = new RelayPoint( http.request.raw.url ); }; +util.inherits( Router, events.EventEmitter ); + Router.prototype.addRoute = function( name, _route, _action, _status ) { this.routes[ name ] = { @@ -97,7 +105,7 @@ Router.prototype.setRoute = function( _route, _match ) , inputs: this.inputs // Re-route function - , reroute: function( target, direct ) + , reRoute: function( target, direct ) { Dragonfly.Log( "Reroute: " + target @@ -105,8 +113,10 @@ Router.prototype.setRoute = function( _route, _match ) ); this.relaying = new RelayPoint( target, direct ); this.routable = true; - this.reroute = true; + this.reRoute = true; + this.emit( "Route" ); }.bind( this ) }; }; + module.exports = Router; diff --git a/net/WebFrame.js b/net/WebFrame.js index 1389507..209fe5d 100644 --- a/net/WebFrame.js +++ b/net/WebFrame.js @@ -12,6 +12,7 @@ var Framework = function( garden ) var Router = require( "./Router" ); this.router = new Router( garden ); this.router.addRoute( "404", false, "404" ); + this.router.addListener( "Route", this.parseResult.bind( this ) ); this.handlers = { "404": function() @@ -59,7 +60,7 @@ Framework.prototype.addHandler = function( name, method ) Framework.prototype.parseResult = function() { - while( this.router.routable ) + if( this.router.routable ) { var method = this.router.route(); if( method ) @@ -69,14 +70,14 @@ Framework.prototype.parseResult = function() if( this.handlers[ method ] ) { this.handlers[ method ]( this.router.routeObj ); - continue; + return; } } else if( method === false ) { Dragonfly.Log( "No route is defined to handle this URI", Dragonfly.Spheres.THERMO ); - this.router.routeObj.reroute( "404", true ); - continue; + this.router.routeObj.reRoute( "404", true ); + return; } throw new FatalError( "Relay handler \"" + method + "\" is not defined" );