摘自----<<基于MVC的 Javascript Web 富应用开发>>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
/*
首先定义个空对象,并初始化绑定方法和触发方法.
*/
var Events = {
bind: function(){
if ( !this.o ) this.o = $({});
this.o.bind.apply(this.o, arguments);
},
trigger: function(){
if ( !this.o ) this.o = $({});
this.o.trigger.apply(this.o, arguments);
}
};
var StateMachine = function(){};
StateMachine.fn = StateMachine.prototype;
$.extend(StateMachine.fn, Events);
/*
定义StateMachine的原型add方法
*/
StateMachine.fn.add = function(controller){
this.bind("change", function(e, current){
/*在空对象上绑定change事件
注意:controller对象是传入的add方法的参数.
因此,如果调用多个add方法的话,会绑定同个change事件的,多个方法。
*/
//这里会编立所有的change事件的方法,如果和当前传入的参数current相等。则activate
if (controller == current)
controller.activate();
else
controller.deactivate();
});
/*
这里同样会因为多个controller,定义多个Mactive方法
*/
controller.Mactive = $.proxy(function(){
console.log("Mactive");
this.trigger("change", controller);
}, this);
};
var con1 = {
activate: function(){
console.log("controller 1 activated");
},
deactivate: function(){
console.log("controller 1 deactivated");
}
};
var con2 = {
activate: function(){
console.log("controller 2 activated");
},
deactivate: function(){
console.log("controller 2 deactivated");
}
};
var sm = new StateMachine;
/*
这里实现两个add方法,则会出现两个change事件,实现内容不同
*/
sm.add(con1);
sm.add(con2);
/*
这里虽然调用的con2的Mactive方法,但是trigger引发的
是空对象this.o的所有的change事件,遍历进行比较,从而得出结果
*/
con2.Mactive();
</script>
</head>
<body>
</body>
</html>