Search code examples
javascriptjqueryscopeobject-literal

acessing Jquery object variable inside object literal function


I'm not able to understand why can't I check the .change() method of a jquery object stored in a variable. Is this a syntax error? Did I lost the context?

Here's my code:

var MyObj = {

    //declaration
    reference : $('#reference'),
    observeReference : function() {

        //The following line is not tracking the .change() method. 
        //Not sure why... And I didn't any get console error!
        this.reference.change(function() {
            var opt = $('#reference option:selected').text();

            if (opt === 'other' || opt === 'reference') {
                $('#input_other').fadeIn();
            } else{
                $('#input_other').fadeOut();
                $('#input_other_bx').val('');
            };
        }.bind(this));      
    },
    init: function() {
        this.observeReference();
    }
};

$(document).ready(function() {
     MyObj.init();
});

Solution

  • If $('#reference') execute before document ready, it will get a jquery object which length = 0.

    init method will execute after document ready, so assign reference in init method .

    var MyObj = {
    
    //declaration
    reference : null,
    ...
    
    init: function() {
        this.reference = $('#reference');
        this.observeReference();
    }