代码可复用性是程序员追求的最终目的,而在变化多端且有与众不同的语法中如何构建库和所谓的模块开发。
抽象出库code
(function($,exports){
var mod = function(includes){
if(includes) this.include(includes)
}
mod.fn = mod.prototype
mod.fn.proxy = function(func){
return $.proxy(func,this)
}
mod.fn.load = function(func){
$(this.proxy(func))
}
mod.fn.include = function(ob){
$.extend(this,ob)
}
exports.Controller = mod
})(jQuery,window)
模块引用Controller代码
jQuery(function($){
searchView = new Controller({
elements:{
"input[type=search]":"searchInput",
"form":"searchForm"
},
init:function(element){
this.el = $(element);
this.refreshElements();
this.searchForm.click(this.proxy(this.search));
},
search:function(){
console.log("Searching:",this.searchInput.val());
return false;
},
$:function(selector){
return $(selector,this.el);
},
refreshElements:function(){
for(var key in this.elements){
this[this.elements[key]] = this.$(key);
}
}
});
});