1

I have an event handler which is bound to a 'change' event. The problem is, functions within that function cannot access any elements of the parent function

Process.prototype.handleCheckboxChange = function(event) {
    var rgbs = []
    $(':checked').each(function(index,element) {
       var color = [0,3,4];
       rgbs.push(color);
    })
}

I have been reading all around the place about closures, but everything I have seen seems to indicate that an inner function should be able to access its parents local variables, whereas this is not the case here: rgbs is undefined.

It may be of use to know that when binding (with jQuery's bind()) I am using closures to set the this keyword to the original object (in a way I don't really understand), although the problem was the same when I was not doing this:

Process.prototype.doBinding = function() {
   $('checkbox').bind('change', function(event) {self.handleCheckboxChange(event)})
}

Any ideas on what I am doing wrong and how I can access rgbs?

4
  • rgbs seems a private variable inside the function - where are you trying to access it? Commented Jun 27, 2011 at 9:18
  • 1
    This should work (apart from that the first snippet is not valid JavaScript and that you didn't define self in the second one). rgbs is visible inside the each callback. Please provide a jsfiddle.net demo. Commented Jun 27, 2011 at 9:19
  • 1
    Are you sure handleCheckboxChange is even executed? Commented Jun 27, 2011 at 9:24
  • Thanks, indeed it is working. I actually simplified what I was doing here (and ended up masking the problem). The problem was simply that if you don't actually use a variable (in this case rgbs) within the inner function, then in the Google Chrome debugger at least, if you try to reference it it tells you it is undefined. I am not sure why it does this, but the moral of the story it seesm is don't rely on the debugger to tell you whether a variable is defined, and don't over simplify examples for stackoverflow! Commented Jun 27, 2011 at 10:12

0

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.