Kranu
Kranu

Reputation: 2567

Access overridden variables from parent function

I'm wondering if there's a simpler solution to my current workaround.

Javascript example:

var data= {
  'key1':'value1'
};

$.each(data,function foo() {
  alert(this); //alerts 'value1'
  $('#element').click(function()) {
    alert(this); //alerts something else
  }
});

The way to fix this would be:

var data= {
  'key1':'value1'
};


$.each(data,function foo() {
  alert(this); //alerts 'value1'

  var this_original=this;

  $('#element').click(function()) {
    alert(this_original); //alerts 'value1'
  }
});

This solves the problem, but it is not very clean. I was wondering if there was a nice Javascript/jQuery method to get the value of the original this inside of the child function. Something like: parentFunction.this

Upvotes: 0

Views: 592

Answers (3)

lsuarez
lsuarez

Reputation: 4992

Please use the answer from Martin Jespersen. However...

Using jQuery's .proxy() function as requested:

var data = {
    "key1": "value1"
};

$.each(data, function(i, obj) {
    alert(this); //alerts 'value1'
    this.onClick = function() {
        alert(this);
    }

    $('#element').click($.proxy(this, "onClick"));
});

Here is a fiddle example.

Please keep in mind you'd probably want to have a way to change the selector for where you're binding the click event, I'm sure.

Upvotes: 1

Genady Sergeev
Genady Sergeev

Reputation: 1650

Use jQuery.proxy. You can use the following code:

 var data= {
  'key1':'value1'
};

$.each(data,function foo() {
  alert(this); //alerts 'value1'
  $('#element').click($.proxy(function() {
    alert(this); }, this);
});

Upvotes: -1

Martin Jespersen
Martin Jespersen

Reputation: 26183

Don't use this, use the arguments instead:

var data= {
  'key1':'value1'
};

$.each(data,function foo(idx,val) {
  alert(val); //alerts 'value1'
  $('#element').click(function() {
    alert(val); //alerts 'value1'
  });
});

Upvotes: 2

Related Questions