[英]jQuery Pattern - is this valid or is there a better way?
我已经整理了一下是否属于这种javascript组织,并且想知道我是否在此处遗漏了这个要点,或者是否有更优雅的方法来做到这一点。
基本上,我将所有内容包装在一个函数(对象)中,然后在该对象上设置方法,然后实例化包装对象的实例并传入任何选项和依赖项。
我有一种预感,有一种方法可以自动运行.init()
以及可以进行的其他一些调整。 我做对了吗?
function AppModuleCore(){
var AppModuleCore = this; //keep internals sane
// Various global vars, objects
AppModuleCore.defaultOptions = {};
AppModuleCore.init = function(opts) {
// todo: that thing where you extend an options object a la juery
AppModuleCore.bindEvents();
};
AppModuleCore.bindEvents = function() {
// bind events here, send to functions within AppModuleCore.<FUNCTIONNAME>();
// Example:
$("a#clicker").unbind("click");
$("a#clicker").click(function(event){
AppModuleCore.handleClickerClick(event);
});
};
AppModuleCore.handleClickerClick = function(event){
alert("clicker was clicked");
};
}
// --------------------------------------------------------------------
// instantiate AppModuleCore object and initialize with opts,
// dependency injection
// --------------------------------------------------------------------
$(document).ready(function(){
AppModuleCore = new AppModuleCore;
var options = {};
AppModuleCore.init(options);
});
好,几点
只有将代码包装在构造函数中才有意义
您的代码不具备这些特征。 我说这是因为您的jQuery选择器a#clicker
是硬编码的,所以我假设您不想将相同的事件多次绑定到它们?
您最好使用一个函数(也许是您的init)或一个对象常量来限制您的范围。
function init( options ) {
var defaultsOptions = {};
var privateVar = 'only in this scope';
//extend your default options with options here
//using jquery
options = $.extend( defaultOptions, options );
// this function is completely private to this scope
function privatefunction() {
//do stuff
}
function handleClickerClick( event ){
alert("clicker was clicked");
}
// you don't need to wrap your handler in an anonymous function unless
// you're doing some work to the event before forwarding:- just give a
// reference to your handler
// the handler has access to other members of this scope, we're in a closure
$(options.selector).click( handleClickerClick );
//etc
}
init( {selector: 'a#clicker'} );
关于风格注:当别名this
具有相同名称的构造函数,然后添加方法的别名,它乍看上去像要添加静态方法来构造。 这可能会使以后查看您的代码却没有注意到别名的人感到困惑。
function C() {
// a static method i.e a property of the constructor, C not objects created with it
// it is a bit wierd that it is defined in the constructor but not unheard of
C.staticMethod = function(){};
//quite plainly a method of objects of this type, easy to understand
this.method = function(){};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.