MarioVW MarioVW - 6 months ago 98
Javascript Question

Pass additional parameters to jQuery each() callback

I'm working on an app that will present surveys to the user. The markup looks something like this:

<body>
<div class="question" id="q1">
Question 1
</div>
<div class="question" id="q2">
Question 2
</div>
<!-- etc -->
</body>


I want to construct the JavaScript objects from the DOM using jQuery, so in the
Survey
constructor I'm traversing the jQuery set using the
each()
method. The problem is that within the callback function I'm unable to get a reference to the
Survey
object in order to append each
Question
object to the
Survey.questions
array. How can get a reference to the
Survey
object? Is there a way to pass an additional parameter (e.g. a reference to the
Survey
object) to the callback function?

function Survey() {
this.questions = new Array;
$('.question').each(function(i) { (/* Survey object */).questions.push(new Question(this)); });
}

function Question(element) {
this.element = $(element);
}

Answer

You should be able to create a reference to your survey before you iterate over the questions.

function Survey() {
    this.questions = new Array();
    var survey = this;
    $('.question').each(function(i) {
        survey.questions.push(new Question(this));
    });
}

function Question(element) {
    this.element = $(element);
}

var survey = new Survey();

$.each(survey.questions, function() {
    $("ul").append("<li>" + this.element.text() + "</li>");
});

Working example on jsfiddle

Comments