timpone
timpone

Reputation: 19969

jQuery each and do I need to create a closure here?

I have the following (shortened the array) that uses jQuery and Underscore:

var all_methods = ['locations', 'items', 'by-cocktails'];
var to_methods = [];
$.each(all_methods, (function (key, val) {
    if ($('.lm-search-options[data-action=' + val + ']').hasClass('del')) {
        console.log('to remove: ' + val); // <- only the last piece is moved out despite multiple pieces being here
        to_methods = _.without(all_methods, val);
    }
}));

The behavior I'm seeing is that only the last of the selected dom elements is removed (yes, I know this isn't going to win any software design awards). For example, if 'locations' and 'items' are to be removed, only 'items' is removed. Is the behavior I'm seeing due to the fact that there needs to be a new closure here?

Upvotes: 0

Views: 54

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

var $opts = $('.lm-search-options');
var to_methods = _.filter(all_methods, function(val){
    return !$opts.filter('[data-action=' + val + ']').hasClass('del')
})

Upvotes: 1

Related Questions