arnisritins
arnisritins

Reputation: 1340

Event handling within the JavaScript object

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!

Upvotes: 1

Views: 102

Answers (2)

Ben McCormick
Ben McCormick

Reputation: 25728

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...
    });
}

Upvotes: 2

Vivin Paliath
Vivin Paliath

Reputation: 95588

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);
}

Upvotes: 3

Related Questions