开发者

Underscore each method returning values

开发者 https://www.devze.com 2023-04-13 06:50 出处:网络
This is a stripped down example of what I\'m trying to do. I\'m trying to get my wrappe开发者_StackOverflow社区r function myElements to return the elements coming from the underscore each iterator. I

This is a stripped down example of what I'm trying to do. I'm trying to get my wrappe开发者_StackOverflow社区r 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
    });
}


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
  }
}


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; }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号