Browse files

change `first()` and `last()` to return a new Zepto object instead of…

… mutating
  • Loading branch information...
1 parent d664ccb commit 54a05bb530e2acdb6f9acfa25c80efb53e481366 @mislav mislav committed Dec 20, 2010
Showing with 20 additions and 17 deletions.
  1. +5 −4 README.rdoc
  2. +2 −2 src/zepto.js
  3. +13 −11 test/zepto.html
View
9 README.rdoc
@@ -40,10 +40,11 @@ Context and .find calls are equivalent:
get(): return array of all elements found
get(0): return first element found
- size(): the number of elements found
- each(callback): iterate over array of all elements found
- index('selector'): return an integer indicating the position of 'selector' in array of all elements found
- first(): remove all but the first element from the list of found elements
+ size(): the number of elements in collection
+ each(callback): iterate over collection, calling callback for every element
+ index('selector'): the position of element matching 'selector' in the current collection
+ first(): new collection containing only the first matched element
+ last(): new collection containing only the last matched element
find('selector'): find all children/grandchildren that match the given selector
closest('selector'): traverses the DOM upwards to find the first matching element
View
4 src/zepto.js
@@ -62,8 +62,8 @@ var Zepto = (function() {
is: function(selector){
return this.length > 0 && $(this.dom[0]).filter(selector).length > 0;
},
- first: function(callback){ this.dom = compact([this.dom[0]]); return this },
- last: function() { this.dom = compact([this.dom[this.length - 1]]); return this },
+ first: function(){ return $(this.get(0)) },
+ last: function(){ return $(this.get(this.length - 1)) },
find: function(selector){
return $(this.dom.map(function(el){ return $$(el, selector) }).reduce(function(a,b){ return a.concat(b) }, []));
},
View
24 test/zepto.html
@@ -236,28 +236,30 @@
var zepto = $('h1,p');
t.assertLength(5, zepto);
- zepto.first();
- t.assertLength(1, zepto);
- t.assertEqual('H1', zepto.get(0).tagName);
+ var zepto2 = zepto.first();
+ t.refuteIdentical(zepto, zepto2);
+ t.assertLength(5, zepto);
+
+ t.assertLength(1, zepto2);
+ t.assertEqual('H1', zepto2.get(0).tagName);
- t.assertLength(0, $('blah'));
- t.assertLength(0, $('blah').first());
+ t.assertLength(0, $('nonexistent').first());
},
testLast: function(t){
var zepto = $('h1,p');
t.assertLength(5, zepto);
- zepto.last();
+ var zepto2 = zepto.last();
+ t.refuteIdentical(zepto, zepto2);
+ t.assertLength(5, zepto);
- t.assertLength(1, zepto);
- t.assertEqual('P', zepto.get(0).tagName);
+ t.assertLength(1, zepto2);
+ t.assertEqual('P', zepto2.get(0).tagName);
- t.assertLength(0, $('blah'));
- t.assertLength(0, $('blah').first());
+ t.assertLength(0, $('nonexistent').last());
},
-
testCompact: function(t){
var nodes = $('p');
nodes.dom = [nodes.get(0), null, undefined, nodes.get(0)];

0 comments on commit 54a05bb

Please sign in to comment.