1

I'm trying to call a blur function on a variable assigned to a jquery object (an input field). How do I call the function on the variable?

var someObject = {
    day: $('#dayInputField'), // input text field

    init:function(){
       console.log("this.day" + this.day); // outputs object
       this.validateField();

    },
    validateField : function(){

      //this gets triggered - but I need to reference the variable
      $('#dayInputField').blur(function(){
       console.log("This gets triggered");
      };

      // this doesn't get triggered - how do I target the variable? 

      this.day.blur(function(){
        console.log("doesn't work");  
      }); 



    }
}

I have also tried -

$(this.day).blur
$(this).day.blur 
someObject.day.blur
$(day, this).blur 

Any help would be appreciated! thanks

Andy E
  • 338,112
  • 86
  • 474
  • 445
Matt
  • 1,140
  • 2
  • 10
  • 17

1 Answers1

1

UPDATE:

My previous answer was incorrect, as you can access properties of your object from a member function using this. The situation that I was describing is different. You wouldn't be able to do this, for example:

var someObject = {
   day: 'some value',
   day2: day
};

But yours is fine. In fact, as noted in your comment below, the problem turned out to be that someObject.init() was called from outside document.ready().


Previous answer:

Yes, you cannot refer to a property of an object before the object is initialized1. You may want to consider using the Module Pattern (a.k.a. the Yahoo Module Pattern) as a solution:

var someObject = (function () {
   var day = $('#dayInputField');

   return {
      init: function () {
         console.log("this.day" + this.day); // outputs object
         this.validateField();   
      },

      validateField: function () {    

         //this gets triggered - but I need to reference the variable
         $('#dayInputField').blur(function(){
            console.log("This gets triggered");
         };

         // now this doesn get triggered
         day.blur(function(){
            console.log("it works");  
         }); 
      }
   };
})();

// Use someObject as you were doing before:
someObject.init();
someObject.validateField();

1 Stack Overflow: How can a Javascript object refer to values in itself?

Community
  • 1
  • 1
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • Unbelievable. It was outside of the document ready - I was calling the someObject.init() method from within document.ready. Just included the object within the document ready , and it works perfectly. Thanks for your prompt response - just needed a poke in the right direction - and will try the Module pattern. Brilliant, thanks again. – Matt Aug 21 '10 at 12:22
  • @Matt: Glad you solved it. Note that my previous description was incorrect. Updated my answer in attempt to correct the mess :) ... (Sorry wasn't thinking) – Daniel Vassallo Aug 21 '10 at 12:33