使用局部上下文创建控制器对象

创建绑定this上下文环境的并且可重用的控制器对象,

//this使用局部上下文基础模型
(function($, exports){
 var mod = function(includes){
  if(includes) this.include(includes);
 };
 mod.fn = mod.prototype;

 //将函数上下文this绑定到mod上
 mod.fn.proxy = function(func){
  return $.proxy(func, this);
 };

 //documentContent加载完后执行相应的func回调
 mod.fn.load = function(func){
  $(this.proxy(func));
 };

 //扩展prototype的方法
 mod.fn.include = function(ob){
  $.extend(this, ob);
 };

 //导出为Controller全局对象
 exports.Controller = mod;
})(jQuery, window);

//给局部上下文模型扩展方法
Controller.fn.unload = function(func){
 jQuery(window).bind('unload', this.proxy(func));
};


//创建Controller对象模块
(function($, Controller){
var mod = new Controller;

mod.toggleClass = function(e){
 console.log(this);
 this.view.toggleClass('over', e.data);
};

//文档加载完毕,可视作window.onload
mod.load(function(){
 this.view = $('#view');

 //绑定mod实例到this.goggleClass,以防止toggleClass内的this指向mouseover事件函数
 this.view.bind('mouseover', true, this.proxy(this.toggleClass));
 this.view.bind('mouseout', false, this.proxy(this.toggleClass));
});
var abc = function(aa){
 console.log(1111);
};
mod.include({abc:abc});


//test 创建第二个控制器对象
var mod1 = new Controller();
console.log(mod1);


})(jQuery, Controller);
================================我是分割 线==========================================
 
第一步:创建控制器模型
这里最主要的是使用了jquery的$.proxy函数来实现上下文的绑定,并且使用exports.Controller方式来爆露导出mod方式,减少了全局对象的污染
第二步:生成控制器模型对象
每一个控制器内都可创建了控制器模型的实例,这样就通过prototype继承方式继承了load等所有函数

 

posted @ 2013-01-28 20:17  池中物王二狗  阅读(257)  评论(0编辑  收藏  举报
转载入注明博客园 王二狗Sheldon Email: willian12345@126.com https://github.com/willian12345