有限状态机
var ctrl1 = { activate: function() { console.log("ctrl1-active"); }, deactivate: function() { console.log("ctrl1-deactive"); } }; var ctrl2 = { activate: function() { console.log("ctrl2-active"); }, deactivate: function() { console.log("ctrl2-deactive"); } }; var ctrl3 = { activate: function() { console.log("ctrl3-active"); }, deactivate: function() { console.log("ctrl3-deactive"); } };
ctrl1,ctrl2,ctrl3表示控制器,当我们要在多个控制器之间切换视图时,就需要引入有限状态机技术.
function Statemachine() {}; var extend = (function() { var F = function() {}; return function(C, P) { F.prototype = P.prototype; C.prototype = new F(); C.uper = P; C.prototype.constructor = C; }; })(); // EventProxy is an Event.js extend(Statemachine, EventProxy); Statemachine.fn = Statemachine.prototype; Statemachine.fn.add = functino(controller) { this.on("change", function(current) { if (controller == current) { controller.activate(); } else { controller.deactivate(); } }); contrlller.active = function() { this.trigger("change", controller); }.bind(this); };
触发方式很简单
var sm = new Statemachine; sm.add(ctrl1); sm.add(ctrl2); sm.add(ctrl3); ctrl1.active(); // sm.trigger("change", ctrl1);
把状态和路由建立关系则可以构建单页面应用了.