schumacherj
schumacherj

Reputation: 1324

What does jQuery's $.each with three arguments do, and how can I translate it to pure JS?

I'm trying to remove JQuery from a project I inherited and I have stumbled upon this line of code which doesn't really make sense.

$.each(options.reservationOptions,this._addToSelect, [select]);

What does $.each() do when there are 3 things passed to it. The first is an object, the second is a function, and the third is a var.

Here is the [select] init:

var select = L.DomUtil.create('select', 'booking-select ' + options.RoomName, reservationContainer);

Here is the function:

_addToSelect: function (select) {
    try {
        var value = this.value;
        var text = this.text;
        if (text) {
            var option = $("<option>").addClass('booking-option').text(text);
            //var option = L.DomUtil.create('option', 'booking-option');
            //option.innerText = text;
            if ( value )
                option.val(value);
            //option.value = value;
            option.appendTo(select);
            //select.appendChild(option.get());

            //var optionsList = select.options || select;
            //optionsList.add(option.get());
        }
    } catch (ex) {
        console.log('could not add option to select ' + ex.message);
    }

Upvotes: 0

Views: 158

Answers (2)

adeneo
adeneo

Reputation: 318302

It iterates, the first argument is the array or object, the second is the callback, and the third is the arguments passed in to the callback. In a loop you'd do the same thing with (assuming array)

options.reservationOptions.forEach(function(item) {

    this._addToSelect.apply(item, [select]);

}.bind(this));

Here's a short version of what jQuery does

$.each = function (obj, callback, args) {
    var value, 
        i       = 0,
        length  = obj.length,
        isArray = isArraylike(obj);

    if (args) {
        if (isArray) {
            for (; i < length; i++) {
                value = callback.apply(obj[i], args);

                if (value === false) {
                    break;
                }
            }
        } else {
            for (i in obj) {
                value = callback.apply(obj[i], args);

                if (value === false) {
                    break;
                }
            }
        }
    }
}

Upvotes: 2

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

forEach takes 2 arguments, callback and context – https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Array/forEach

options.reservationOptions.forEach(function(option) {
    this.options.reservationOptions(option);
}, this);

Upvotes: 0

Related Questions