Created
November 26, 2014 04:45
-
-
Save tetsuharuohzeki/1d2eb87c5b470d2677d4 to your computer and use it in GitHub Desktop.
Fluxパターンでルーターを作る
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var crossroads = require("crossroads"); | |
var Dispatcher = require("flux").Dispatcher; | |
var EventEmitter = require("events").EventEmitter; | |
var hasher = require("hasher"); | |
var RoutingActionCreator = { | |
/** | |
* @param {string} path | |
*/ | |
moveTo: function (path) { | |
RoutingDispather.dispatch({ | |
actionType: "Routing::moveTo", | |
path: path, | |
}); | |
}, | |
}; | |
var RoutingDispather = { | |
_dispatcher: new Dispatcher(), | |
dispatch: function (val) { | |
this._dispatcher.dispatch(val); | |
}, | |
register: function (callback) { | |
this._dispatcher.register(callback); | |
}, | |
}; | |
var RoutingStore = { | |
_emitter: new EventEmitter(), | |
EVENT_CHANGE: "RoutingStore::change", | |
dispatchToken: null, | |
setup: function () { | |
crossroads.addRoute("/bar", () => { | |
// route毎に必要な処理 | |
}); | |
crossroads.addRoute("/foo", () => { | |
// route毎に必要な処理 | |
}); | |
// 各route毎の処理が終わったら, storeのchangeイベントを起こす | |
crossroads.routed.add((path) => { | |
this.emitChange(path); | |
}); | |
}, | |
addChangeListener: function (callback) { | |
this._emitter.addListener(RoutingStore.EVENT_CHANGE, callback); | |
}, | |
emitChange: function (path) { | |
this._emitter.emit(this.EVENT_CHANGE, path); | |
}, | |
}; | |
RoutingStore.dispatchToken = RoutingDispatcher.register(function(payload){ | |
switch (payload.actionType) { | |
case "Routing::moveTo": | |
var path = payload.path; | |
crossroads.parse(path); | |
break; | |
} | |
}); | |
var URIHistoryView = function () { | |
this.init(); | |
}; | |
URIHistoryView.prototype = { | |
init: function () { | |
RoutingStore.addChangeListener(this.onChange.bind(this)); | |
// URLの変更に応じてActionを起こす | |
var parseHash = function parseHash(newHash){ | |
RoutingActionCreator.moveTo(newHash); | |
}; | |
hasher.initialized.add(parseHash); | |
hasher.changed.add(parseHash); | |
hasher.init(); | |
}, | |
onChange: function (path) { | |
// Storeのchangeイベントのコールバック変更のため, URLの変更だけする. | |
hasher.changed.active = false; | |
hasher.setHash(path); | |
hasher.changed.active = true; | |
}, | |
}; | |
function main() { | |
RoutingStore.setup(); | |
new URIHistoryView(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment