views:

35

answers:

2

Hi there!

I got a simple question about jQuery but rather javascript approaches in general...

Is it ok, to do this? :

this._checkedTexts.length = 0; // <- array belonging to "me"
var contextCheckedTexts = this._checkedTexts;

$('#valueContainer input:checked').each(function() {
  contextCheckedTexts.push($(this).text());
});

Since 'this' points to the element, I am using a closure here to keep additional context for the 'each'-handler around.

Is this the way 'how it's done' or could there be any risk involved using a closure in this way (memoryleak-wise....)?

What other options are there?

I find it very practical - but also I'm always a little worried about introducing reference-count-problems when using closures - which will be hard to find later on.

Thanks for any input!

Kind regards, Wolfgang

A: 

I don't know what you are trying to achieve but your codes may also be done like this,

this._checkedTexts.length = 0; // <- array belonging to "me"

var arr = $('#valueContainer input:checked').map(function() {
  return $(this).text();
}).get();

this._checkedTexts = this._checkedTexts.concat(arr);
Reigel
Pretty awesome :) I love jQuery more and more... thanks for the hint!! - but still, the question remains: is it ok (and the usual approach) to use closures for context to a function that has the 'wrong' this-pointer?
Wolfgang
yes it's fine to use closures... but if you do it, do it like this, `var self = this;`... so that you can call other properties using `self`. e.g. `self._checkedTexts.push($(this).text());. with that, you already eliminate `var contextCheckedTexts = this._checkedTexts;`...
Reigel
... sounds like a plan - and also if I'm doing it this way every time, there is probably less confusion :) thank you!
Wolfgang
A: 

It seems to be fine as jQuery methods like each, map, grep does not support context by default (there're bound to the current jQuery object). However you can create you own bind function that will apply context to functions (but in this case you dontn't have to as you use default context to get the elements text).

fantactuka