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!

1
  • 5
    Attach the event in the initialize method. Commented Apr 30, 2013 at 19:49

2 Answers 2

3

You should be calling on inside the initialize function. Since the outer function is executing immediately (as you realized yourself), element is undefined. So you should only be calling on on it, after the variable has been defined:

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

    config = $.extend(config, options);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Stick it in the initialize method.

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.