jQuery模式 - 这是有效的还是有更好的方法?

时间:2011-02-24 18:12:41

标签: javascript jquery architecture design-patterns

如果我陷入这种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);

});

1 个答案:

答案 0 :(得分:1)

好的,有些要点 如果

,只将代码包装在构造函数中才有意义
  1. 您将要实例化多个
  2. 您将要调用的对象上有“公共”方法
  3. 您的代码没有展示这些特征。我这样说是因为你的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(){};
    
    }