Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Stop iteration in $.fn.each() when the callback returns false #632

Closed
wants to merge 2 commits into
from

Conversation

Projects
None yet
3 participants
Contributor

mitio commented Nov 5, 2012

As per the documentation, the iteration in $.fn.each() should stop when the iteration callback returns fasle. This way it will also conform to the jQuery API.

Currently, $.fn.each delegates to Array.prototype.forEach. I didn't find a way to stop the iteration when using forEach, thus I had to look for another solution. I wanted to keep the iteration in native code and found out that Array.prototype.every might do the job.

I didn't expose this in the public interface of Zepto and thus the somewhat odd emptyArray.every.call pattern.

Any notes on the implementation are welcome.

@mitio mitio Stop iteration in $.fn.each() when the callback returns false
As per the documentation, the iteration in $.fn.each() should
stop when the iteration callback returns fasle.

Use Array.prototype.every() to emulate this behaviour while
still keeping the iteration code native.
4d69f67

@staabm staabm and 1 other commented on an outdated diff Nov 5, 2012

@@ -350,7 +350,10 @@ var Zepto = (function() {
})
},
each: function(callback){
- this.forEach(function(el, idx){ callback.call(el, idx, el) })
+ emptyArray.every.call(this, function(el, idx){
+ if (callback.call(el, idx, el) === false) return false
@staabm

staabm Nov 5, 2012

could be shortened to `return !!callback.call(el, idx, el)``

@mitio

mitio Nov 5, 2012

Contributor

Hehe, that's right... :) However, it has to be callback.call(el, idx, el) !== false, because only a false return value, and not a null or a undefined one, should stop the iteration.

I'll change it.

@staabm

staabm Nov 5, 2012

hm you are right... so you could write it with 3x !

@mitio

mitio Nov 5, 2012

Contributor

I'm not sure what you mean by "3x !". If it's !!!something, I don't know how this would help. Anyway, I pushed a simpler version, based on your suggestion. Thanks for that!

@staabm

staabm Nov 5, 2012

yep looks much better now.

!! will cast the returned value to a boolean and ! would make sure we have the negation, but I think your solution is easier to read..

@mitio mitio Compact $.fn.each a bit
It's a bit simpler now, as per this suggestion by @staabm:
#632 (comment)
7aeb12b
Collaborator

mislav commented Nov 25, 2012

Good catch, thanks! Pulled

@mislav mislav closed this Nov 25, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment