query.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. define(["./_base/kernel", "./has", "./dom", "./on", "./_base/array", "./_base/lang", "./selector/_loader", "./selector/_loader!default"],
  2. function(dojo, has, dom, on, array, lang, loader, defaultEngine){
  3. "use strict";
  4. has.add("array-extensible", function(){
  5. // test to see if we can extend an array (not supported in old IE)
  6. return lang.delegate([], {length: 1}).length == 1 && !has("bug-for-in-skips-shadowed");
  7. });
  8. var ap = Array.prototype, aps = ap.slice, apc = ap.concat, forEach = array.forEach;
  9. var tnl = function(/*Array*/ a, /*dojo/NodeList?*/ parent, /*Function?*/ NodeListCtor){
  10. // summary:
  11. // decorate an array to make it look like a `dojo/NodeList`.
  12. // a:
  13. // Array of nodes to decorate.
  14. // parent:
  15. // An optional parent NodeList that generated the current
  16. // list of nodes. Used to call _stash() so the parent NodeList
  17. // can be accessed via end() later.
  18. // NodeListCtor:
  19. // An optional constructor function to use for any
  20. // new NodeList calls. This allows a certain chain of
  21. // NodeList calls to use a different object than dojo/NodeList.
  22. var nodeList = new (NodeListCtor || this._NodeListCtor || nl)(a);
  23. return parent ? nodeList._stash(parent) : nodeList;
  24. };
  25. var loopBody = function(f, a, o){
  26. a = [0].concat(aps.call(a, 0));
  27. o = o || dojo.global;
  28. return function(node){
  29. a[0] = node;
  30. return f.apply(o, a);
  31. };
  32. };
  33. // adapters
  34. var adaptAsForEach = function(f, o){
  35. // summary:
  36. // adapts a single node function to be used in the forEach-type
  37. // actions. The initial object is returned from the specialized
  38. // function.
  39. // f: Function
  40. // a function to adapt
  41. // o: Object?
  42. // an optional context for f
  43. return function(){
  44. this.forEach(loopBody(f, arguments, o));
  45. return this; // Object
  46. };
  47. };
  48. var adaptAsMap = function(f, o){
  49. // summary:
  50. // adapts a single node function to be used in the map-type
  51. // actions. The return is a new array of values, as via `dojo/_base/array.map`
  52. // f: Function
  53. // a function to adapt
  54. // o: Object?
  55. // an optional context for f
  56. return function(){
  57. return this.map(loopBody(f, arguments, o));
  58. };
  59. };
  60. var adaptAsFilter = function(f, o){
  61. // summary:
  62. // adapts a single node function to be used in the filter-type actions
  63. // f: Function
  64. // a function to adapt
  65. // o: Object?
  66. // an optional context for f
  67. return function(){
  68. return this.filter(loopBody(f, arguments, o));
  69. };
  70. };
  71. var adaptWithCondition = function(f, g, o){
  72. // summary:
  73. // adapts a single node function to be used in the map-type
  74. // actions, behaves like forEach() or map() depending on arguments
  75. // f: Function
  76. // a function to adapt
  77. // g: Function
  78. // a condition function, if true runs as map(), otherwise runs as forEach()
  79. // o: Object?
  80. // an optional context for f and g
  81. return function(){
  82. var a = arguments, body = loopBody(f, a, o);
  83. if(g.call(o || dojo.global, a)){
  84. return this.map(body); // self
  85. }
  86. this.forEach(body);
  87. return this; // self
  88. };
  89. };
  90. var NodeList = function(array){
  91. // summary:
  92. // Array-like object which adds syntactic
  93. // sugar for chaining, common iteration operations, animation, and
  94. // node manipulation. NodeLists are most often returned as the
  95. // result of dojo/query() calls.
  96. // description:
  97. // NodeList instances provide many utilities that reflect
  98. // core Dojo APIs for Array iteration and manipulation, DOM
  99. // manipulation, and event handling. Instead of needing to dig up
  100. // functions in the dojo package, NodeLists generally make the
  101. // full power of Dojo available for DOM manipulation tasks in a
  102. // simple, chainable way.
  103. // example:
  104. // create a node list from a node
  105. // | require(["dojo/query", "dojo/dom"
  106. // | ], function(query, dom){
  107. // | query.NodeList(dom.byId("foo"));
  108. // | });
  109. // example:
  110. // get a NodeList from a CSS query and iterate on it
  111. // | require(["dojo/on", "dojo/dom"
  112. // | ], function(on, dom){
  113. // | var l = query(".thinger");
  114. // | l.forEach(function(node, index, nodeList){
  115. // | console.log(index, node.innerHTML);
  116. // | });
  117. // | });
  118. // example:
  119. // use native and Dojo-provided array methods to manipulate a
  120. // NodeList without needing to use dojo.* functions explicitly:
  121. // | require(["dojo/query", "dojo/dom-construct", "dojo/dom"
  122. // | ], function(query, domConstruct, dom){
  123. // | var l = query(".thinger");
  124. // | // since NodeLists are real arrays, they have a length
  125. // | // property that is both readable and writable and
  126. // | // push/pop/shift/unshift methods
  127. // | console.log(l.length);
  128. // | l.push(domConstruct.create("span"));
  129. // |
  130. // | // dojo's normalized array methods work too:
  131. // | console.log( l.indexOf(dom.byId("foo")) );
  132. // | // ...including the special "function as string" shorthand
  133. // | console.log( l.every("item.nodeType == 1") );
  134. // |
  135. // | // NodeLists can be [..] indexed, or you can use the at()
  136. // | // function to get specific items wrapped in a new NodeList:
  137. // | var node = l[3]; // the 4th element
  138. // | var newList = l.at(1, 3); // the 2nd and 4th elements
  139. // | });
  140. // example:
  141. // chainability is a key advantage of NodeLists:
  142. // | require(["dojo/query", "dojo/NodeList-dom"
  143. // | ], function(query){
  144. // | query(".thinger")
  145. // | .onclick(function(e){ /* ... */ })
  146. // | .at(1, 3, 8) // get a subset
  147. // | .style("padding", "5px")
  148. // | .forEach(console.log);
  149. // | });
  150. var isNew = this instanceof nl && has("array-extensible");
  151. if(typeof array == "number"){
  152. array = Array(array);
  153. }
  154. var nodeArray = (array && "length" in array) ? array : arguments;
  155. if(isNew || !nodeArray.sort){
  156. // make sure it's a real array before we pass it on to be wrapped
  157. var target = isNew ? this : [],
  158. l = target.length = nodeArray.length;
  159. for(var i = 0; i < l; i++){
  160. target[i] = nodeArray[i];
  161. }
  162. if(isNew){
  163. // called with new operator, this means we are going to use this instance and push
  164. // the nodes on to it. This is usually much faster since the NodeList properties
  165. // don't need to be copied (unless the list of nodes is extremely large).
  166. return target;
  167. }
  168. nodeArray = target;
  169. }
  170. // called without new operator, use a real array and copy prototype properties,
  171. // this is slower and exists for back-compat. Should be removed in 2.0.
  172. lang._mixin(nodeArray, nlp);
  173. nodeArray._NodeListCtor = function(array){
  174. // call without new operator to preserve back-compat behavior
  175. return nl(array);
  176. };
  177. return nodeArray;
  178. };
  179. var nl = NodeList, nlp = nl.prototype =
  180. has("array-extensible") ? [] : {};// extend an array if it is extensible
  181. // expose adapters and the wrapper as private functions
  182. nl._wrap = nlp._wrap = tnl;
  183. nl._adaptAsMap = adaptAsMap;
  184. nl._adaptAsForEach = adaptAsForEach;
  185. nl._adaptAsFilter = adaptAsFilter;
  186. nl._adaptWithCondition = adaptWithCondition;
  187. // mass assignment
  188. // add array redirectors
  189. forEach(["slice", "splice"], function(name){
  190. var f = ap[name];
  191. //Use a copy of the this array via this.slice() to allow .end() to work right in the splice case.
  192. // CANNOT apply ._stash()/end() to splice since it currently modifies
  193. // the existing this array -- it would break backward compatibility if we copy the array before
  194. // the splice so that we can use .end(). So only doing the stash option to this._wrap for slice.
  195. nlp[name] = function(){ return this._wrap(f.apply(this, arguments), name == "slice" ? this : null); };
  196. });
  197. // concat should be here but some browsers with native NodeList have problems with it
  198. // add array.js redirectors
  199. forEach(["indexOf", "lastIndexOf", "every", "some"], function(name){
  200. var f = array[name];
  201. nlp[name] = function(){ return f.apply(dojo, [this].concat(aps.call(arguments, 0))); };
  202. });
  203. lang.extend(NodeList, {
  204. // copy the constructors
  205. constructor: nl,
  206. _NodeListCtor: nl,
  207. toString: function(){
  208. // Array.prototype.toString can't be applied to objects, so we use join
  209. return this.join(",");
  210. },
  211. _stash: function(parent){
  212. // summary:
  213. // private function to hold to a parent NodeList. end() to return the parent NodeList.
  214. //
  215. // example:
  216. // How to make a `dojo/NodeList` method that only returns the third node in
  217. // the dojo/NodeList but allows access to the original NodeList by using this._stash:
  218. // | require(["dojo/query", "dojo/_base/lang", "dojo/NodeList", "dojo/NodeList-dom"
  219. // | ], function(query, lang){
  220. // | lang.extend(NodeList, {
  221. // | third: function(){
  222. // | var newNodeList = NodeList(this[2]);
  223. // | return newNodeList._stash(this);
  224. // | }
  225. // | });
  226. // | // then see how _stash applies a sub-list, to be .end()'ed out of
  227. // | query(".foo")
  228. // | .third()
  229. // | .addClass("thirdFoo")
  230. // | .end()
  231. // | // access to the orig .foo list
  232. // | .removeClass("foo")
  233. // | });
  234. //
  235. this._parent = parent;
  236. return this; // dojo/NodeList
  237. },
  238. on: function(eventName, listener){
  239. // summary:
  240. // Listen for events on the nodes in the NodeList. Basic usage is:
  241. //
  242. // example:
  243. // | require(["dojo/query"
  244. // | ], function(query){
  245. // | query(".my-class").on("click", listener);
  246. // This supports event delegation by using selectors as the first argument with the event names as
  247. // pseudo selectors. For example:
  248. // | query("#my-list").on("li:click", listener);
  249. // This will listen for click events within `<li>` elements that are inside the `#my-list` element.
  250. // Because on supports CSS selector syntax, we can use comma-delimited events as well:
  251. // | query("#my-list").on("li button:mouseover, li:click", listener);
  252. // | });
  253. var handles = this.map(function(node){
  254. return on(node, eventName, listener); // TODO: apply to the NodeList so the same selector engine is used for matches
  255. });
  256. handles.remove = function(){
  257. for(var i = 0; i < handles.length; i++){
  258. handles[i].remove();
  259. }
  260. };
  261. return handles;
  262. },
  263. end: function(){
  264. // summary:
  265. // Ends use of the current `NodeList` by returning the previous NodeList
  266. // that generated the current NodeList.
  267. // description:
  268. // Returns the `NodeList` that generated the current `NodeList`. If there
  269. // is no parent NodeList, an empty NodeList is returned.
  270. // example:
  271. // | require(["dojo/query", "dojo/NodeList-dom"
  272. // | ], function(query){
  273. // | query("a")
  274. // | .filter(".disabled")
  275. // | // operate on the anchors that only have a disabled class
  276. // | .style("color", "grey")
  277. // | .end()
  278. // | // jump back to the list of anchors
  279. // | .style(...)
  280. // | });
  281. //
  282. if(this._parent){
  283. return this._parent;
  284. }else{
  285. //Just return empty list.
  286. return new this._NodeListCtor(0);
  287. }
  288. },
  289. // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Methods
  290. // FIXME: handle return values for #3244
  291. // http://trac.dojotoolkit.org/ticket/3244
  292. // FIXME:
  293. // need to wrap or implement:
  294. // join (perhaps w/ innerHTML/outerHTML overload for toString() of items?)
  295. // reduce
  296. // reduceRight
  297. /*=====
  298. slice: function(begin, end){
  299. // summary:
  300. // Returns a new NodeList, maintaining this one in place
  301. // description:
  302. // This method behaves exactly like the Array.slice method
  303. // with the caveat that it returns a `dojo/NodeList` and not a
  304. // raw Array. For more details, see Mozilla's [slice
  305. // documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice)
  306. // begin: Integer
  307. // Can be a positive or negative integer, with positive
  308. // integers noting the offset to begin at, and negative
  309. // integers denoting an offset from the end (i.e., to the left
  310. // of the end)
  311. // end: Integer?
  312. // Optional parameter to describe what position relative to
  313. // the NodeList's zero index to end the slice at. Like begin,
  314. // can be positive or negative.
  315. return this._wrap(a.slice.apply(this, arguments));
  316. },
  317. splice: function(index, howmany, item){
  318. // summary:
  319. // Returns a new NodeList, manipulating this NodeList based on
  320. // the arguments passed, potentially splicing in new elements
  321. // at an offset, optionally deleting elements
  322. // description:
  323. // This method behaves exactly like the Array.splice method
  324. // with the caveat that it returns a `dojo/NodeList` and not a
  325. // raw Array. For more details, see Mozilla's [splice
  326. // documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice)
  327. // For backwards compatibility, calling .end() on the spliced NodeList
  328. // does not return the original NodeList -- splice alters the NodeList in place.
  329. // index: Integer
  330. // begin can be a positive or negative integer, with positive
  331. // integers noting the offset to begin at, and negative
  332. // integers denoting an offset from the end (i.e., to the left
  333. // of the end)
  334. // howmany: Integer?
  335. // Optional parameter to describe what position relative to
  336. // the NodeList's zero index to end the slice at. Like begin,
  337. // can be positive or negative.
  338. // item: Object...?
  339. // Any number of optional parameters may be passed in to be
  340. // spliced into the NodeList
  341. return this._wrap(a.splice.apply(this, arguments)); // dojo/NodeList
  342. },
  343. indexOf: function(value, fromIndex){
  344. // summary:
  345. // see `dojo/_base/array.indexOf()`. The primary difference is that the acted-on
  346. // array is implicitly this NodeList
  347. // value: Object
  348. // The value to search for.
  349. // fromIndex: Integer?
  350. // The location to start searching from. Optional. Defaults to 0.
  351. // description:
  352. // For more details on the behavior of indexOf, see Mozilla's
  353. // [indexOf
  354. // docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf)
  355. // returns:
  356. // Positive Integer or 0 for a match, -1 of not found.
  357. return d.indexOf(this, value, fromIndex); // Integer
  358. },
  359. lastIndexOf: function(value, fromIndex){
  360. // summary:
  361. // see `dojo/_base/array.lastIndexOf()`. The primary difference is that the
  362. // acted-on array is implicitly this NodeList
  363. // description:
  364. // For more details on the behavior of lastIndexOf, see
  365. // Mozilla's [lastIndexOf
  366. // docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf)
  367. // value: Object
  368. // The value to search for.
  369. // fromIndex: Integer?
  370. // The location to start searching from. Optional. Defaults to 0.
  371. // returns:
  372. // Positive Integer or 0 for a match, -1 of not found.
  373. return d.lastIndexOf(this, value, fromIndex); // Integer
  374. },
  375. every: function(callback, thisObject){
  376. // summary:
  377. // see `dojo/_base/array.every()` and the [Array.every
  378. // docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every).
  379. // Takes the same structure of arguments and returns as
  380. // dojo/_base/array.every() with the caveat that the passed array is
  381. // implicitly this NodeList
  382. // callback: Function
  383. // the callback
  384. // thisObject: Object?
  385. // the context
  386. return d.every(this, callback, thisObject); // Boolean
  387. },
  388. some: function(callback, thisObject){
  389. // summary:
  390. // Takes the same structure of arguments and returns as
  391. // `dojo/_base/array.some()` with the caveat that the passed array is
  392. // implicitly this NodeList. See `dojo/_base/array.some()` and Mozilla's
  393. // [Array.some
  394. // documentation](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some).
  395. // callback: Function
  396. // the callback
  397. // thisObject: Object?
  398. // the context
  399. return d.some(this, callback, thisObject); // Boolean
  400. },
  401. =====*/
  402. concat: function(item){
  403. // summary:
  404. // Returns a new NodeList comprised of items in this NodeList
  405. // as well as items passed in as parameters
  406. // description:
  407. // This method behaves exactly like the Array.concat method
  408. // with the caveat that it returns a `NodeList` and not a
  409. // raw Array. For more details, see the [Array.concat
  410. // docs](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/concat)
  411. // item: Object?
  412. // Any number of optional parameters may be passed in to be
  413. // spliced into the NodeList
  414. //return this._wrap(apc.apply(this, arguments));
  415. // the line above won't work for the native NodeList, or for Dojo NodeLists either :-(
  416. // implementation notes:
  417. // Array.concat() doesn't recognize native NodeLists or Dojo NodeLists
  418. // as arrays, and so does not inline them into a unioned array, but
  419. // appends them as single entities. Both the original NodeList and the
  420. // items passed in as parameters must be converted to raw Arrays
  421. // and then the concatenation result may be re-_wrap()ed as a Dojo NodeList.
  422. var t = aps.call(this, 0),
  423. m = array.map(arguments, function(a){
  424. return aps.call(a, 0);
  425. });
  426. return this._wrap(apc.apply(t, m), this); // dojo/NodeList
  427. },
  428. map: function(/*Function*/ func, /*Function?*/ obj){
  429. // summary:
  430. // see `dojo/_base/array.map()`. The primary difference is that the acted-on
  431. // array is implicitly this NodeList and the return is a
  432. // NodeList (a subclass of Array)
  433. return this._wrap(array.map(this, func, obj), this); // dojo/NodeList
  434. },
  435. forEach: function(callback, thisObj){
  436. // summary:
  437. // see `dojo/_base/array.forEach()`. The primary difference is that the acted-on
  438. // array is implicitly this NodeList. If you want the option to break out
  439. // of the forEach loop, use every() or some() instead.
  440. forEach(this, callback, thisObj);
  441. // non-standard return to allow easier chaining
  442. return this; // dojo/NodeList
  443. },
  444. filter: function(/*String|Function*/ filter){
  445. // summary:
  446. // "masks" the built-in javascript filter() method (supported
  447. // in Dojo via `dojo/_base/array.filter`) to support passing a simple
  448. // string filter in addition to supporting filtering function
  449. // objects.
  450. // filter:
  451. // If a string, a CSS rule like ".thinger" or "div > span".
  452. // example:
  453. // "regular" JS filter syntax as exposed in `dojo/_base/array.filter`:
  454. // | require(["dojo/query", "dojo/NodeList-dom"
  455. // | ], function(query){
  456. // | query("*").filter(function(item){
  457. // | // highlight every paragraph
  458. // | return (item.nodeName == "p");
  459. // | }).style("backgroundColor", "yellow");
  460. // | });
  461. // example:
  462. // the same filtering using a CSS selector
  463. // | require(["dojo/query", "dojo/NodeList-dom"
  464. // | ], function(query){
  465. // | query("*").filter("p").styles("backgroundColor", "yellow");
  466. // | });
  467. var a = arguments, items = this, start = 0;
  468. if(typeof filter == "string"){ // inline'd type check
  469. items = query._filterResult(this, a[0]);
  470. if(a.length == 1){
  471. // if we only got a string query, pass back the filtered results
  472. return items._stash(this); // dojo/NodeList
  473. }
  474. // if we got a callback, run it over the filtered items
  475. start = 1;
  476. }
  477. return this._wrap(array.filter(items, a[start], a[start + 1]), this); // dojo/NodeList
  478. },
  479. instantiate: function(/*String|Object*/ declaredClass, /*Object?*/ properties){
  480. // summary:
  481. // Create a new instance of a specified class, using the
  482. // specified properties and each node in the NodeList as a
  483. // srcNodeRef.
  484. // example:
  485. // Grabs all buttons in the page and converts them to dijit/form/Button's.
  486. // | var buttons = query("button").instantiate(Button, {showLabel: true});
  487. var c = lang.isFunction(declaredClass) ? declaredClass : lang.getObject(declaredClass);
  488. properties = properties || {};
  489. return this.forEach(function(node){
  490. new c(properties, node);
  491. }); // dojo/NodeList
  492. },
  493. at: function(/*===== index =====*/){
  494. // summary:
  495. // Returns a new NodeList comprised of items in this NodeList
  496. // at the given index or indices.
  497. //
  498. // index: Integer...
  499. // One or more 0-based indices of items in the current
  500. // NodeList. A negative index will start at the end of the
  501. // list and go backwards.
  502. //
  503. // example:
  504. // Shorten the list to the first, second, and third elements
  505. // | require(["dojo/query"
  506. // | ], function(query){
  507. // | query("a").at(0, 1, 2).forEach(fn);
  508. // | });
  509. //
  510. // example:
  511. // Retrieve the first and last elements of a unordered list:
  512. // | require(["dojo/query"
  513. // | ], function(query){
  514. // | query("ul > li").at(0, -1).forEach(cb);
  515. // | });
  516. //
  517. // example:
  518. // Do something for the first element only, but end() out back to
  519. // the original list and continue chaining:
  520. // | require(["dojo/query"
  521. // | ], function(query){
  522. // | query("a").at(0).onclick(fn).end().forEach(function(n){
  523. // | console.log(n); // all anchors on the page.
  524. // | })
  525. // | });
  526. var t = new this._NodeListCtor(0);
  527. forEach(arguments, function(i){
  528. if(i < 0){ i = this.length + i; }
  529. if(this[i]){ t.push(this[i]); }
  530. }, this);
  531. return t._stash(this); // dojo/NodeList
  532. }
  533. });
  534. function queryForEngine(engine, NodeList){
  535. var query = function(/*String*/ query, /*String|DOMNode?*/ root){
  536. // summary:
  537. // Returns nodes which match the given CSS selector, searching the
  538. // entire document by default but optionally taking a node to scope
  539. // the search by. Returns an instance of NodeList.
  540. if(typeof root == "string"){
  541. root = dom.byId(root);
  542. if(!root){
  543. return new NodeList([]);
  544. }
  545. }
  546. var results = typeof query == "string" ? engine(query, root) : query ? (query.end && query.on) ? query : [query] : [];
  547. if(results.end && results.on){
  548. // already wrapped
  549. return results;
  550. }
  551. return new NodeList(results);
  552. };
  553. query.matches = engine.match || function(node, selector, root){
  554. // summary:
  555. // Test to see if a node matches a selector
  556. return query.filter([node], selector, root).length > 0;
  557. };
  558. // the engine provides a filtering function, use it to for matching
  559. query.filter = engine.filter || function(nodes, selector, root){
  560. // summary:
  561. // Filters an array of nodes. Note that this does not guarantee to return a NodeList, just an array.
  562. return query(selector, root).filter(function(node){
  563. return array.indexOf(nodes, node) > -1;
  564. });
  565. };
  566. if(typeof engine != "function"){
  567. var search = engine.search;
  568. engine = function(selector, root){
  569. // Slick does it backwards (or everyone else does it backwards, probably the latter)
  570. return search(root || document, selector);
  571. };
  572. }
  573. return query;
  574. }
  575. var query = queryForEngine(defaultEngine, NodeList);
  576. /*=====
  577. query = function(selector, context){
  578. // summary:
  579. // This modules provides DOM querying functionality. The module export is a function
  580. // that can be used to query for DOM nodes by CSS selector and returns a NodeList
  581. // representing the matching nodes.
  582. // selector: String
  583. // A CSS selector to search for.
  584. // context: String|DomNode?
  585. // An optional context to limit the searching scope. Only nodes under `context` will be
  586. // scanned.
  587. // example:
  588. // add an onclick handler to every submit button in the document
  589. // which causes the form to be sent via Ajax instead:
  590. // | require(["dojo/query", "dojo/request", "dojo/dom-form", "dojo/dom-construct", "dojo/dom-style"
  591. // | ], function(query, request, domForm, domConstruct, domStyle){
  592. // | query("input[type='submit']").on("click", function(e){
  593. // | e.preventDefault(); // prevent sending the form
  594. // | var btn = e.target;
  595. // | request.post("http://example.com/", {
  596. // | data: domForm.toObject(btn.form)
  597. // | }).then(function(response){
  598. // | // replace the form with the response
  599. // | domConstruct.create(div, {innerHTML: response}, btn.form, "after");
  600. // | domStyle.set(btn.form, "display", "none");
  601. // | });
  602. // | });
  603. // | });
  604. //
  605. // description:
  606. // dojo/query is responsible for loading the appropriate query engine and wrapping
  607. // its results with a `NodeList`. You can use dojo/query with a specific selector engine
  608. // by using it as a plugin. For example, if you installed the sizzle package, you could
  609. // use it as the selector engine with:
  610. // | require(["dojo/query!sizzle"], function(query){
  611. // | query("div")...
  612. //
  613. // The id after the ! can be a module id of the selector engine or one of the following values:
  614. //
  615. // - acme: This is the default engine used by Dojo base, and will ensure that the full
  616. // Acme engine is always loaded.
  617. //
  618. // - css2: If the browser has a native selector engine, this will be used, otherwise a
  619. // very minimal lightweight selector engine will be loaded that can do simple CSS2 selectors
  620. // (by #id, .class, tag, and [name=value] attributes, with standard child or descendant (>)
  621. // operators) and nothing more.
  622. //
  623. // - css2.1: If the browser has a native selector engine, this will be used, otherwise the
  624. // full Acme engine will be loaded.
  625. //
  626. // - css3: If the browser has a native selector engine with support for CSS3 pseudo
  627. // selectors (most modern browsers except IE8), this will be used, otherwise the
  628. // full Acme engine will be loaded.
  629. //
  630. // - Or the module id of a selector engine can be used to explicitly choose the selector engine
  631. //
  632. // For example, if you are using CSS3 pseudo selectors in module, you can specify that
  633. // you will need support them with:
  634. // | require(["dojo/query!css3"], function(query){
  635. // | query('#t > h3:nth-child(odd)')...
  636. //
  637. // You can also choose the selector engine/load configuration by setting the query-selector:
  638. // For example:
  639. // | <script data-dojo-config="query-selector:'css3'" src="dojo.js"></script>
  640. //
  641. return new NodeList(); // dojo/NodeList
  642. };
  643. =====*/
  644. // the query that is returned from this module is slightly different than dojo.query,
  645. // because dojo.query has to maintain backwards compatibility with returning a
  646. // true array which has performance problems. The query returned from the module
  647. // does not use true arrays, but rather inherits from Array, making it much faster to
  648. // instantiate.
  649. dojo.query = queryForEngine(defaultEngine, function(array){
  650. // call it without the new operator to invoke the back-compat behavior that returns a true array
  651. return NodeList(array); // dojo/NodeList
  652. });
  653. query.load = function(id, parentRequire, loaded){
  654. // summary:
  655. // can be used as AMD plugin to conditionally load new query engine
  656. // example:
  657. // | require(["dojo/query!custom"], function(qsa){
  658. // | // loaded selector/custom.js as engine
  659. // | qsa("#foobar").forEach(...);
  660. // | });
  661. loader.load(id, parentRequire, function(engine){
  662. loaded(queryForEngine(engine, NodeList));
  663. });
  664. };
  665. dojo._filterQueryResult = query._filterResult = function(nodes, selector, root){
  666. return new NodeList(query.filter(nodes, selector, root));
  667. };
  668. dojo.NodeList = query.NodeList = NodeList;
  669. return query;
  670. });