1

I've created some kind of JavaScript object with the such design pattern:

var MyObject = (function(){

    var element;
    var config = {
        // Defaults...
    };

    function initialize(id, options){
        element = $(id);
        config = $.extend(config, options);
    }

    function method(){
        // Some code...
    }

    element.on('click', function(){
        // Some actions when clicked on element...
    });

    return {
        initialize: initialize,
        // Other public methods...
    };

})();

And that's how object is initialized:

MyObject.initialize('#someId');

Script works great, however an error occurs, when I try to add some events for element. As I realized, an anonymous function (function(){ ... })(); is executed immediatelly, but initialization of variable elementcomes after.

So, how can I implement an event handling exactly for this JavaScript object pattern?

Thanks!

4

2 回答 2

3

您应该on在函数内部调用initialize。由于外部函数会立即执行(正如您自己意识到的那样),element所以 is undefined. 所以你应该只on在定义变量之后调用它:

function initialize(id, options){
    element = $(id);
    element.on('click', function() {
        ...
    });   

    config = $.extend(config, options);
}
于 2013-04-30T19:50:03.967 回答
2

将其粘贴在初始化方法中。

function initialize(id, options){
    element = $(id);
    config = $.extend(config, options);


    element.on('click', function(){
        // Some actions when clicked on element...
    });
}
于 2013-04-30T19:51:12.887 回答