3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
9 * @extends Ext.BoxComponent
10 * A mechanism for displaying data using custom layout templates and formatting. DataView uses an {@link Ext.XTemplate}
11 * as its internal templating mechanism, and is bound to an {@link Ext.data.Store}
12 * so that as the data in the store changes the view is automatically updated to reflect the changes. The view also
13 * provides built-in behavior for many common events that can occur for its contained items including click, doubleclick,
14 * mouseover, mouseout, etc. as well as a built-in selection model. <b>In order to use these features, an {@link #itemSelector}
15 * config must be provided for the DataView to determine what nodes it will be working with.</b>
17 * <p>The example below binds a DataView to a {@link Ext.data.Store} and renders it into an {@link Ext.Panel}.</p>
19 var store = new Ext.data.JsonStore({
20 url: 'get-images.php',
24 {name:'size', type: 'float'},
25 {name:'lastmod', type:'date', dateFormat:'timestamp'}
30 var tpl = new Ext.XTemplate(
31 '<tpl for=".">',
32 '<div class="thumb-wrap" id="{name}">',
33 '<div class="thumb"><img src="{url}" title="{name}"></div>',
34 '<span class="x-editable">{shortName}</span></div>',
36 '<div class="x-clear"></div>'
39 var panel = new Ext.Panel({
46 title:'Simple DataView',
48 items: new Ext.DataView({
53 overClass:'x-view-over',
54 itemSelector:'div.thumb-wrap',
55 emptyText: 'No images to display'
58 panel.render(document.body);
61 * Create a new DataView
62 * @param {Object} config The config object
65 Ext.DataView = Ext.extend(Ext.BoxComponent, {
67 * @cfg {String/Array} tpl
68 * The HTML fragment or an array of fragments that will make up the template used by this DataView. This should
69 * be specified in the same format expected by the constructor of {@link Ext.XTemplate}.
72 * @cfg {Ext.data.Store} store
73 * The {@link Ext.data.Store} to bind this DataView to.
76 * @cfg {String} itemSelector
77 * <b>This is a required setting</b>. A simple CSS selector (e.g. <tt>div.some-class</tt> or
78 * <tt>span:first-child</tt>) that will be used to determine what nodes this DataView will be
82 * @cfg {Boolean} multiSelect
83 * True to allow selection of more than one item at a time, false to allow selection of only a single item
84 * at a time or no selection at all, depending on the value of {@link #singleSelect} (defaults to false).
87 * @cfg {Boolean} singleSelect
88 * True to allow selection of exactly one item at a time, false to allow no selection at all (defaults to false).
89 * Note that if {@link #multiSelect} = true, this value will be ignored.
92 * @cfg {Boolean} simpleSelect
93 * True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl,
94 * false to force the user to hold Ctrl or Shift to select more than on item (defaults to false).
97 * @cfg {String} overClass
98 * A CSS class to apply to each item in the view on mouseover (defaults to undefined).
101 * @cfg {String} loadingText
102 * A string to display during data load operations (defaults to undefined). If specified, this text will be
103 * displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's
104 * contents will continue to display normally until the new data is loaded and the contents are replaced.
107 * @cfg {String} selectedClass
108 * A CSS class to apply to each selected item in the view (defaults to 'x-view-selected').
110 selectedClass : "x-view-selected",
112 * @cfg {String} emptyText
113 * The text to display in the view when there is no data to display (defaults to '').
118 * @cfg {Boolean} deferEmptyText True to defer emptyText being applied until the store's first load
120 deferEmptyText: true,
122 * @cfg {Boolean} trackOver True to enable mouseenter and mouseleave events
127 * @cfg {Boolean} blockRefresh Set this to true to ignore datachanged events on the bound store. This is useful if
128 * you wish to provide custom transition animations via a plugin (defaults to false)
136 initComponent : function(){
137 Ext.DataView.superclass.initComponent.call(this);
138 if(Ext.isString(this.tpl) || Ext.isArray(this.tpl)){
139 this.tpl = new Ext.XTemplate(this.tpl);
145 * Fires before a click is processed. Returns false to cancel the default action.
146 * @param {Ext.DataView} this
147 * @param {Number} index The index of the target node
148 * @param {HTMLElement} node The target node
149 * @param {Ext.EventObject} e The raw event object
154 * Fires when a template node is clicked.
155 * @param {Ext.DataView} this
156 * @param {Number} index The index of the target node
157 * @param {HTMLElement} node The target node
158 * @param {Ext.EventObject} e The raw event object
163 * Fires when the mouse enters a template node. trackOver:true or an overClass must be set to enable this event.
164 * @param {Ext.DataView} this
165 * @param {Number} index The index of the target node
166 * @param {HTMLElement} node The target node
167 * @param {Ext.EventObject} e The raw event object
172 * Fires when the mouse leaves a template node. trackOver:true or an overClass must be set to enable this event.
173 * @param {Ext.DataView} this
174 * @param {Number} index The index of the target node
175 * @param {HTMLElement} node The target node
176 * @param {Ext.EventObject} e The raw event object
180 * @event containerclick
181 * Fires when a click occurs and it is not on a template node.
182 * @param {Ext.DataView} this
183 * @param {Ext.EventObject} e The raw event object
188 * Fires when a template node is double clicked.
189 * @param {Ext.DataView} this
190 * @param {Number} index The index of the target node
191 * @param {HTMLElement} node The target node
192 * @param {Ext.EventObject} e The raw event object
197 * Fires when a template node is right clicked.
198 * @param {Ext.DataView} this
199 * @param {Number} index The index of the target node
200 * @param {HTMLElement} node The target node
201 * @param {Ext.EventObject} e The raw event object
205 * @event containercontextmenu
206 * Fires when a right click occurs that is not on a template node.
207 * @param {Ext.DataView} this
208 * @param {Ext.EventObject} e The raw event object
210 "containercontextmenu",
212 * @event selectionchange
213 * Fires when the selected nodes change.
214 * @param {Ext.DataView} this
215 * @param {Array} selections Array of the selected nodes
220 * @event beforeselect
221 * Fires before a selection is made. If any handlers return false, the selection is cancelled.
222 * @param {Ext.DataView} this
223 * @param {HTMLElement} node The node to be selected
224 * @param {Array} selections Array of currently selected nodes
229 this.store = Ext.StoreMgr.lookup(this.store);
230 this.all = new Ext.CompositeElementLite();
231 this.selected = new Ext.CompositeElementLite();
235 afterRender : function(){
236 Ext.DataView.superclass.afterRender.call(this);
238 this.mon(this.getTemplateTarget(), {
239 "click": this.onClick,
240 "dblclick": this.onDblClick,
241 "contextmenu": this.onContextMenu,
245 if(this.overClass || this.trackOver){
246 this.mon(this.getTemplateTarget(), {
247 "mouseover": this.onMouseOver,
248 "mouseout": this.onMouseOut,
254 this.bindStore(this.store, true);
259 * Refreshes the view by reloading the data from the store and re-rendering the template.
261 refresh : function() {
262 this.clearSelections(false, true);
263 var el = this.getTemplateTarget();
265 var records = this.store.getRange();
266 if(records.length < 1){
267 if(!this.deferEmptyText || this.hasSkippedEmptyText){
268 el.update(this.emptyText);
272 this.tpl.overwrite(el, this.collectData(records, 0));
273 this.all.fill(Ext.query(this.itemSelector, el.dom));
274 this.updateIndexes(0);
276 this.hasSkippedEmptyText = true;
279 getTemplateTarget: function(){
284 * Function which can be overridden to provide custom formatting for each Record that is used by this
285 * DataView's {@link #tpl template} to render each node.
286 * @param {Array/Object} data The raw data object that was used to create the Record.
287 * @param {Number} recordIndex the index number of the Record being prepared for rendering.
288 * @param {Record} record The Record being prepared for rendering.
289 * @return {Array/Object} The formatted data in a format expected by the internal {@link #tpl template}'s overwrite() method.
290 * (either an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}))
292 prepareData : function(data){
297 * <p>Function which can be overridden which returns the data object passed to this
298 * DataView's {@link #tpl template} to render the whole DataView.</p>
299 * <p>This is usually an Array of data objects, each element of which is processed by an
300 * {@link Ext.XTemplate XTemplate} which uses <tt>'<tpl for=".">'</tt> to iterate over its supplied
301 * data object as an Array. However, <i>named</i> properties may be placed into the data object to
302 * provide non-repeating data such as headings, totals etc.</p>
303 * @param {Array} records An Array of {@link Ext.data.Record}s to be rendered into the DataView.
304 * @param {Number} startIndex the index number of the Record being prepared for rendering.
305 * @return {Array} An Array of data objects to be processed by a repeating XTemplate. May also
306 * contain <i>named</i> properties.
308 collectData : function(records, startIndex){
310 for(var i = 0, len = records.length; i < len; i++){
311 r[r.length] = this.prepareData(records[i].data, startIndex+i, records[i]);
317 bufferRender : function(records){
318 var div = document.createElement('div');
319 this.tpl.overwrite(div, this.collectData(records));
320 return Ext.query(this.itemSelector, div);
324 onUpdate : function(ds, record){
325 var index = this.store.indexOf(record);
327 var sel = this.isSelected(index);
328 var original = this.all.elements[index];
329 var node = this.bufferRender([record], index)[0];
331 this.all.replaceElement(index, node, true);
333 this.selected.replaceElement(original, node);
334 this.all.item(index).addClass(this.selectedClass);
336 this.updateIndexes(index, index);
341 onAdd : function(ds, records, index){
342 if(this.all.getCount() === 0){
346 var nodes = this.bufferRender(records, index), n, a = this.all.elements;
347 if(index < this.all.getCount()){
348 n = this.all.item(index).insertSibling(nodes, 'before', true);
349 a.splice.apply(a, [index, 0].concat(nodes));
351 n = this.all.last().insertSibling(nodes, 'after', true);
352 a.push.apply(a, nodes);
354 this.updateIndexes(index);
358 onRemove : function(ds, record, index){
359 this.deselect(index);
360 this.all.removeElement(index, true);
361 this.updateIndexes(index);
362 if (this.store.getCount() === 0){
368 * Refreshes an individual node's data from the store.
369 * @param {Number} index The item's data index in the store
371 refreshNode : function(index){
372 this.onUpdate(this.store, this.store.getAt(index));
376 updateIndexes : function(startIndex, endIndex){
377 var ns = this.all.elements;
378 startIndex = startIndex || 0;
379 endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1));
380 for(var i = startIndex; i <= endIndex; i++){
386 * Returns the store associated with this DataView.
387 * @return {Ext.data.Store} The store
389 getStore : function(){
394 * Changes the data store bound to this view and refreshes it.
395 * @param {Store} store The store to bind to this view
397 bindStore : function(store, initial){
398 if(!initial && this.store){
399 if(store !== this.store && this.store.autoDestroy){
400 this.store.destroy();
402 this.store.un("beforeload", this.onBeforeLoad, this);
403 this.store.un("datachanged", this.onDataChanged, this);
404 this.store.un("add", this.onAdd, this);
405 this.store.un("remove", this.onRemove, this);
406 this.store.un("update", this.onUpdate, this);
407 this.store.un("clear", this.refresh, this);
414 store = Ext.StoreMgr.lookup(store);
417 beforeload: this.onBeforeLoad,
418 datachanged: this.onDataChanged,
420 remove: this.onRemove,
421 update: this.onUpdate,
433 * Calls this.refresh if this.blockRefresh is not true
435 onDataChanged: function() {
436 if (this.blockRefresh !== true) {
437 this.refresh.apply(this, arguments);
442 * Returns the template node the passed child belongs to, or null if it doesn't belong to one.
443 * @param {HTMLElement} node
444 * @return {HTMLElement} The template node
446 findItemFromChild : function(node){
447 return Ext.fly(node).findParent(this.itemSelector, this.getTemplateTarget());
451 onClick : function(e){
452 var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
454 var index = this.indexOf(item);
455 if(this.onItemClick(item, index, e) !== false){
456 this.fireEvent("click", this, index, item, e);
459 if(this.fireEvent("containerclick", this, e) !== false){
460 this.onContainerClick(e);
465 onContainerClick : function(e){
466 this.clearSelections();
470 onContextMenu : function(e){
471 var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
473 this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
475 this.fireEvent("containercontextmenu", this, e);
480 onDblClick : function(e){
481 var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
483 this.fireEvent("dblclick", this, this.indexOf(item), item, e);
488 onMouseOver : function(e){
489 var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
490 if(item && item !== this.lastItem){
491 this.lastItem = item;
492 Ext.fly(item).addClass(this.overClass);
493 this.fireEvent("mouseenter", this, this.indexOf(item), item, e);
498 onMouseOut : function(e){
500 if(!e.within(this.lastItem, true, true)){
501 Ext.fly(this.lastItem).removeClass(this.overClass);
502 this.fireEvent("mouseleave", this, this.indexOf(this.lastItem), this.lastItem, e);
503 delete this.lastItem;
509 onItemClick : function(item, index, e){
510 if(this.fireEvent("beforeclick", this, index, item, e) === false){
513 if(this.multiSelect){
514 this.doMultiSelection(item, index, e);
516 }else if(this.singleSelect){
517 this.doSingleSelection(item, index, e);
524 doSingleSelection : function(item, index, e){
525 if(e.ctrlKey && this.isSelected(index)){
526 this.deselect(index);
528 this.select(index, false);
533 doMultiSelection : function(item, index, e){
534 if(e.shiftKey && this.last !== false){
535 var last = this.last;
536 this.selectRange(last, index, e.ctrlKey);
537 this.last = last; // reset the last
539 if((e.ctrlKey||this.simpleSelect) && this.isSelected(index)){
540 this.deselect(index);
542 this.select(index, e.ctrlKey || e.shiftKey || this.simpleSelect);
548 * Gets the number of selected nodes.
549 * @return {Number} The node count
551 getSelectionCount : function(){
552 return this.selected.getCount();
556 * Gets the currently selected nodes.
557 * @return {Array} An array of HTMLElements
559 getSelectedNodes : function(){
560 return this.selected.elements;
564 * Gets the indexes of the selected nodes.
565 * @return {Array} An array of numeric indexes
567 getSelectedIndexes : function(){
568 var indexes = [], s = this.selected.elements;
569 for(var i = 0, len = s.length; i < len; i++){
570 indexes.push(s[i].viewIndex);
576 * Gets an array of the selected records
577 * @return {Array} An array of {@link Ext.data.Record} objects
579 getSelectedRecords : function(){
580 var r = [], s = this.selected.elements;
581 for(var i = 0, len = s.length; i < len; i++){
582 r[r.length] = this.store.getAt(s[i].viewIndex);
588 * Gets an array of the records from an array of nodes
589 * @param {Array} nodes The nodes to evaluate
590 * @return {Array} records The {@link Ext.data.Record} objects
592 getRecords : function(nodes){
593 var r = [], s = nodes;
594 for(var i = 0, len = s.length; i < len; i++){
595 r[r.length] = this.store.getAt(s[i].viewIndex);
601 * Gets a record from a node
602 * @param {HTMLElement} node The node to evaluate
603 * @return {Record} record The {@link Ext.data.Record} object
605 getRecord : function(node){
606 return this.store.getAt(node.viewIndex);
610 * Clears all selections.
611 * @param {Boolean} suppressEvent (optional) True to skip firing of the selectionchange event
613 clearSelections : function(suppressEvent, skipUpdate){
614 if((this.multiSelect || this.singleSelect) && this.selected.getCount() > 0){
616 this.selected.removeClass(this.selectedClass);
618 this.selected.clear();
621 this.fireEvent("selectionchange", this, this.selected.elements);
627 * Returns true if the passed node is selected, else false.
628 * @param {HTMLElement/Number/Ext.data.Record} node The node, node index or record to check
629 * @return {Boolean} True if selected, else false
631 isSelected : function(node){
632 return this.selected.contains(this.getNode(node));
637 * @param {HTMLElement/Number/Record} node The node, node index or record to deselect
639 deselect : function(node){
640 if(this.isSelected(node)){
641 node = this.getNode(node);
642 this.selected.removeElement(node);
643 if(this.last == node.viewIndex){
646 Ext.fly(node).removeClass(this.selectedClass);
647 this.fireEvent("selectionchange", this, this.selected.elements);
652 * Selects a set of nodes.
653 * @param {Array/HTMLElement/String/Number/Ext.data.Record} nodeInfo An HTMLElement template node, index of a template node,
654 * id of a template node, record associated with a node or an array of any of those to select
655 * @param {Boolean} keepExisting (optional) true to keep existing selections
656 * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
658 select : function(nodeInfo, keepExisting, suppressEvent){
659 if(Ext.isArray(nodeInfo)){
661 this.clearSelections(true);
663 for(var i = 0, len = nodeInfo.length; i < len; i++){
664 this.select(nodeInfo[i], true, true);
667 this.fireEvent("selectionchange", this, this.selected.elements);
670 var node = this.getNode(nodeInfo);
672 this.clearSelections(true);
674 if(node && !this.isSelected(node)){
675 if(this.fireEvent("beforeselect", this, node, this.selected.elements) !== false){
676 Ext.fly(node).addClass(this.selectedClass);
677 this.selected.add(node);
678 this.last = node.viewIndex;
680 this.fireEvent("selectionchange", this, this.selected.elements);
688 * Selects a range of nodes. All nodes between start and end are selected.
689 * @param {Number} start The index of the first node in the range
690 * @param {Number} end The index of the last node in the range
691 * @param {Boolean} keepExisting (optional) True to retain existing selections
693 selectRange : function(start, end, keepExisting){
695 this.clearSelections(true);
697 this.select(this.getNodes(start, end), true);
701 * Gets a template node.
702 * @param {HTMLElement/String/Number/Ext.data.Record} nodeInfo An HTMLElement template node, index of a template node,
703 * the id of a template node or the record associated with the node.
704 * @return {HTMLElement} The node or null if it wasn't found
706 getNode : function(nodeInfo){
707 if(Ext.isString(nodeInfo)){
708 return document.getElementById(nodeInfo);
709 }else if(Ext.isNumber(nodeInfo)){
710 return this.all.elements[nodeInfo];
711 }else if(nodeInfo instanceof Ext.data.Record){
712 var idx = this.store.indexOf(nodeInfo);
713 return this.all.elements[idx];
719 * Gets a range nodes.
720 * @param {Number} start (optional) The index of the first node in the range
721 * @param {Number} end (optional) The index of the last node in the range
722 * @return {Array} An array of nodes
724 getNodes : function(start, end){
725 var ns = this.all.elements;
727 end = !Ext.isDefined(end) ? Math.max(ns.length - 1, 0) : end;
730 for(i = start; i <= end && ns[i]; i++){
734 for(i = start; i >= end && ns[i]; i--){
742 * Finds the index of the passed node.
743 * @param {HTMLElement/String/Number/Record} nodeInfo An HTMLElement template node, index of a template node, the id of a template node
744 * or a record associated with a node.
745 * @return {Number} The index of the node or -1
747 indexOf : function(node){
748 node = this.getNode(node);
749 if(Ext.isNumber(node.viewIndex)){
750 return node.viewIndex;
752 return this.all.indexOf(node);
756 onBeforeLoad : function(){
757 if(this.loadingText){
758 this.clearSelections(false, true);
759 this.getTemplateTarget().update('<div class="loading-indicator">'+this.loadingText+'</div>');
764 onDestroy : function(){
766 this.selected.clear();
767 Ext.DataView.superclass.onDestroy.call(this);
768 this.bindStore(null);
773 * Changes the data store bound to this view and refreshes it. (deprecated in favor of bindStore)
774 * @param {Store} store The store to bind to this view
776 Ext.DataView.prototype.setStore = Ext.DataView.prototype.bindStore;
778 Ext.reg('dataview', Ext.DataView);