[ Underscore each method returning values ]
This is a stripped down example of what I'm trying to do. I'm trying to get my wrapper function myElements
to return the elements coming from the underscore each iterator. I can trace out the values of the els inside the _.each
function but how can I get my function to return those values when called from my buttonClickListener
?
buttonClickListenr: function(event){
if ( $(event.target).is( myElements() )) return;
..// otherwise move on in my event phase
}
myElements: function(){
var filter=['a','b'];
_.each(filter, function(el){
return el
});
}
Answer 1
The each
function will invoke the callback once per element and not group the return values as you expect. Instead you need to store them in a structure which persists after the each
method finishes
Try the following
getNums: function(){
var filter=['20','2'];
var result = [];
_.each(filter, function(num){
result.push(num);
});
return result;
}
EDIT
OP clarified they just want to see if the event.target
is in the array. In that case you just want to use the indexOf
method. For example
getNums: function() {
return ['20', '2'];
},
buttonClickListener: function(event){
if (this.getNums().indexOf(event.target) >= 0) {
// It's present
}
}
Answer 2
What you're trying to do doesn't really make sense. The 'include' operator is probably more useful for you:
if ( _(filter).include($(event.target)) ){ return; }