Permalink
Browse files

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.
  • Loading branch information...
1 parent dea8af9 commit 4d69f67fedc8586096658fb1837ab8ac0b9af869 @mitio committed Nov 5, 2012
Showing with 16 additions and 1 deletion.
  1. +4 −1 src/zepto.js
  2. +12 −0 test/zepto.html
View
@@ -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
+ else return true
+ })
return this
},
filter: function(selector){
View
@@ -698,6 +698,18 @@ <h1>Zepto DOM unit tests</h1>
t.assertEqual(2, index)
},
+ testEachBreak: function(t){
+ var index, tagnames = []
+ $('#eachtest > *').each(function(idx, el){
+ index = idx
+ t.assertIdentical(el, this)
+ tagnames.push(el.tagName.toUpperCase())
+ if (idx == 1) return false
+ })
+ t.assertEqual('SPAN, B', tagnames.join(', '))
+ t.assertEqual(1, index)
+ },
+
testMap: function(t){
var results = $('#eachtest > *').map(function(idx, el) {
t.assertIdentical(el, this)

0 comments on commit 4d69f67

Please sign in to comment.