Roo.View add @event 'preparedata', replaces overwriting the method prepareData.
[roojs1] / Roo / View.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Roo.View
14  * @extends Roo.util.Observable
15  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
16  * This class also supports single and multi selection modes. <br>
17  * Create a data model bound view:
18  <pre><code>
19  var store = new Roo.data.Store(...);
20
21  var view = new Roo.View({
22     el : "my-element",
23     tpl : '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
24  
25     singleSelect: true,
26     selectedClass: "ydataview-selected",
27     store: store
28  });
29
30  // listen for node click?
31  view.on("click", function(vw, index, node, e){
32  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
33  });
34
35  // load XML data
36  dataModel.load("foobar.xml");
37  </code></pre>
38  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
39  * <br><br>
40  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
41  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
42  * 
43  * Note: old style constructor is still suported (container, template, config)
44  * 
45  * @constructor
46  * Create a new View
47  * @param {Object} config The config object
48  * 
49  */
50 Roo.View = function(config, depreciated_tpl, depreciated_config){
51     
52     if (typeof(depreciated_tpl) == 'undefined') {
53         // new way.. - universal constructor.
54         Roo.apply(this, config);
55         this.el  = Roo.get(this.el);
56     } else {
57         // old format..
58         this.el  = Roo.get(config);
59         this.tpl = depreciated_tpl;
60         Roo.apply(this, depreciated_config);
61     }
62      
63     
64     if(typeof(this.tpl) == "string"){
65         this.tpl = new Roo.Template(this.tpl);
66     } else {
67         // support xtype ctors..
68         this.tpl = new Roo.factory(this.tpl, Roo);
69     }
70     
71     
72     this.tpl.compile();
73    
74
75      
76     /** @private */
77     this.addEvents({
78         /**
79          * @event beforeclick
80          * Fires before a click is processed. Returns false to cancel the default action.
81          * @param {Roo.View} this
82          * @param {Number} index The index of the target node
83          * @param {HTMLElement} node The target node
84          * @param {Roo.EventObject} e The raw event object
85          */
86             "beforeclick" : true,
87         /**
88          * @event click
89          * Fires when a template node is clicked.
90          * @param {Roo.View} this
91          * @param {Number} index The index of the target node
92          * @param {HTMLElement} node The target node
93          * @param {Roo.EventObject} e The raw event object
94          */
95             "click" : true,
96         /**
97          * @event dblclick
98          * Fires when a template node is double clicked.
99          * @param {Roo.View} this
100          * @param {Number} index The index of the target node
101          * @param {HTMLElement} node The target node
102          * @param {Roo.EventObject} e The raw event object
103          */
104             "dblclick" : true,
105         /**
106          * @event contextmenu
107          * Fires when a template node is right clicked.
108          * @param {Roo.View} this
109          * @param {Number} index The index of the target node
110          * @param {HTMLElement} node The target node
111          * @param {Roo.EventObject} e The raw event object
112          */
113             "contextmenu" : true,
114         /**
115          * @event selectionchange
116          * Fires when the selected nodes change.
117          * @param {Roo.View} this
118          * @param {Array} selections Array of the selected nodes
119          */
120             "selectionchange" : true,
121     
122         /**
123          * @event beforeselect
124          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
125          * @param {Roo.View} this
126          * @param {HTMLElement} node The node to be selected
127          * @param {Array} selections Array of currently selected nodes
128          */
129             "beforeselect" : true,
130         /**
131          * @event preparedata
132          * Fires on every row to render, to allow you to change the data.
133          * @param {Roo.View} this
134          * @param {Object} data to be rendered (change this)
135          */
136           "preparedata" : true
137         });
138
139     this.el.on({
140         "click": this.onClick,
141         "dblclick": this.onDblClick,
142         "contextmenu": this.onContextMenu,
143         scope:this
144     });
145
146     this.selections = [];
147     this.nodes = [];
148     this.cmp = new Roo.CompositeElementLite([]);
149     if(this.store){
150         this.store = Roo.factory(this.store, Roo.data);
151         this.setStore(this.store, true);
152     }
153     Roo.View.superclass.constructor.call(this);
154 };
155
156 Roo.extend(Roo.View, Roo.util.Observable, {
157     
158      /**
159      * @cfg {Roo.data.Store} store Data store to load data from.
160      */
161     store : false,
162     
163     /**
164      * @cfg {String|Roo.Element} el The container element.
165      */
166     el : '',
167     
168     /**
169      * @cfg {String|Roo.Template} tpl The template used by this View 
170      */
171     tpl : false,
172     
173     /**
174      * @cfg {String} selectedClass The css class to add to selected nodes
175      */
176     selectedClass : "x-view-selected",
177      /**
178      * @cfg {String} emptyText The empty text to show when nothing is loaded.
179      */
180     emptyText : "",
181     /**
182      * @cfg {Boolean} multiSelect Allow multiple selection
183      */
184     
185     multiSelect : false,
186     /**
187      * @cfg {Boolean} singleSelect Allow single selection
188      */
189     singleSelect:  false,
190     
191     /**
192      * Returns the element this view is bound to.
193      * @return {Roo.Element}
194      */
195     getEl : function(){
196         return this.el;
197     },
198
199     /**
200      * Refreshes the view.
201      */
202     refresh : function(){
203         var t = this.tpl;
204         this.clearSelections();
205         this.el.update("");
206         var html = [];
207         var records = this.store.getRange();
208         if(records.length < 1){
209             this.el.update(this.emptyText);
210             return;
211         }
212         for(var i = 0, len = records.length; i < len; i++){
213             var data = this.prepareData(records[i].data, i, records[i]);
214             this.fireEvent("preparedata", this, data, i, records[i]);
215             html[html.length] = t.apply(data);
216         }
217         this.el.update(html.join(""));
218         this.nodes = this.el.dom.childNodes;
219         this.updateIndexes(0);
220     },
221
222     /**
223      * Function to override to reformat the data that is sent to
224      * the template for each node.
225      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
226      * a JSON object for an UpdateManager bound view).
227      */
228     prepareData : function(data){
229         return data;
230     },
231
232     onUpdate : function(ds, record){
233         this.clearSelections();
234         var index = this.store.indexOf(record);
235         var n = this.nodes[index];
236         this.tpl.insertBefore(n, this.prepareData(record.data));
237         n.parentNode.removeChild(n);
238         this.updateIndexes(index, index);
239     },
240
241     onAdd : function(ds, records, index){
242         this.clearSelections();
243         if(this.nodes.length == 0){
244             this.refresh();
245             return;
246         }
247         var n = this.nodes[index];
248         for(var i = 0, len = records.length; i < len; i++){
249             var d = this.prepareData(records[i].data);
250             if(n){
251                 this.tpl.insertBefore(n, d);
252             }else{
253                 this.tpl.append(this.el, d);
254             }
255         }
256         this.updateIndexes(index);
257     },
258
259     onRemove : function(ds, record, index){
260         this.clearSelections();
261         this.el.dom.removeChild(this.nodes[index]);
262         this.updateIndexes(index);
263     },
264
265     /**
266      * Refresh an individual node.
267      * @param {Number} index
268      */
269     refreshNode : function(index){
270         this.onUpdate(this.store, this.store.getAt(index));
271     },
272
273     updateIndexes : function(startIndex, endIndex){
274         var ns = this.nodes;
275         startIndex = startIndex || 0;
276         endIndex = endIndex || ns.length - 1;
277         for(var i = startIndex; i <= endIndex; i++){
278             ns[i].nodeIndex = i;
279         }
280     },
281
282     /**
283      * Changes the data store this view uses and refresh the view.
284      * @param {Store} store
285      */
286     setStore : function(store, initial){
287         if(!initial && this.store){
288             this.store.un("datachanged", this.refresh);
289             this.store.un("add", this.onAdd);
290             this.store.un("remove", this.onRemove);
291             this.store.un("update", this.onUpdate);
292             this.store.un("clear", this.refresh);
293         }
294         if(store){
295           
296             store.on("datachanged", this.refresh, this);
297             store.on("add", this.onAdd, this);
298             store.on("remove", this.onRemove, this);
299             store.on("update", this.onUpdate, this);
300             store.on("clear", this.refresh, this);
301         }
302         
303         if(store){
304             this.refresh();
305         }
306     },
307
308     /**
309      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
310      * @param {HTMLElement} node
311      * @return {HTMLElement} The template node
312      */
313     findItemFromChild : function(node){
314         var el = this.el.dom;
315         if(!node || node.parentNode == el){
316                     return node;
317             }
318             var p = node.parentNode;
319             while(p && p != el){
320             if(p.parentNode == el){
321                 return p;
322             }
323             p = p.parentNode;
324         }
325             return null;
326     },
327
328     /** @ignore */
329     onClick : function(e){
330         var item = this.findItemFromChild(e.getTarget());
331         if(item){
332             var index = this.indexOf(item);
333             if(this.onItemClick(item, index, e) !== false){
334                 this.fireEvent("click", this, index, item, e);
335             }
336         }else{
337             this.clearSelections();
338         }
339     },
340
341     /** @ignore */
342     onContextMenu : function(e){
343         var item = this.findItemFromChild(e.getTarget());
344         if(item){
345             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
346         }
347     },
348
349     /** @ignore */
350     onDblClick : function(e){
351         var item = this.findItemFromChild(e.getTarget());
352         if(item){
353             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
354         }
355     },
356
357     onItemClick : function(item, index, e){
358         if(this.fireEvent("beforeclick", this, index, item, e) === false){
359             return false;
360         }
361         if(this.multiSelect || this.singleSelect){
362             if(this.multiSelect && e.shiftKey && this.lastSelection){
363                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
364             }else{
365                 this.select(item, this.multiSelect && e.ctrlKey);
366                 this.lastSelection = item;
367             }
368             e.preventDefault();
369         }
370         return true;
371     },
372
373     /**
374      * Get the number of selected nodes.
375      * @return {Number}
376      */
377     getSelectionCount : function(){
378         return this.selections.length;
379     },
380
381     /**
382      * Get the currently selected nodes.
383      * @return {Array} An array of HTMLElements
384      */
385     getSelectedNodes : function(){
386         return this.selections;
387     },
388
389     /**
390      * Get the indexes of the selected nodes.
391      * @return {Array}
392      */
393     getSelectedIndexes : function(){
394         var indexes = [], s = this.selections;
395         for(var i = 0, len = s.length; i < len; i++){
396             indexes.push(s[i].nodeIndex);
397         }
398         return indexes;
399     },
400
401     /**
402      * Clear all selections
403      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
404      */
405     clearSelections : function(suppressEvent){
406         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
407             this.cmp.elements = this.selections;
408             this.cmp.removeClass(this.selectedClass);
409             this.selections = [];
410             if(!suppressEvent){
411                 this.fireEvent("selectionchange", this, this.selections);
412             }
413         }
414     },
415
416     /**
417      * Returns true if the passed node is selected
418      * @param {HTMLElement/Number} node The node or node index
419      * @return {Boolean}
420      */
421     isSelected : function(node){
422         var s = this.selections;
423         if(s.length < 1){
424             return false;
425         }
426         node = this.getNode(node);
427         return s.indexOf(node) !== -1;
428     },
429
430     /**
431      * Selects nodes.
432      * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
433      * @param {Boolean} keepExisting (optional) true to keep existing selections
434      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
435      */
436     select : function(nodeInfo, keepExisting, suppressEvent){
437         if(nodeInfo instanceof Array){
438             if(!keepExisting){
439                 this.clearSelections(true);
440             }
441             for(var i = 0, len = nodeInfo.length; i < len; i++){
442                 this.select(nodeInfo[i], true, true);
443             }
444         } else{
445             var node = this.getNode(nodeInfo);
446             if(node && !this.isSelected(node)){
447                 if(!keepExisting){
448                     this.clearSelections(true);
449                 }
450                 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
451                     Roo.fly(node).addClass(this.selectedClass);
452                     this.selections.push(node);
453                     if(!suppressEvent){
454                         this.fireEvent("selectionchange", this, this.selections);
455                     }
456                 }
457             }
458         }
459     },
460
461     /**
462      * Gets a template node.
463      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
464      * @return {HTMLElement} The node or null if it wasn't found
465      */
466     getNode : function(nodeInfo){
467         if(typeof nodeInfo == "string"){
468             return document.getElementById(nodeInfo);
469         }else if(typeof nodeInfo == "number"){
470             return this.nodes[nodeInfo];
471         }
472         return nodeInfo;
473     },
474
475     /**
476      * Gets a range template nodes.
477      * @param {Number} startIndex
478      * @param {Number} endIndex
479      * @return {Array} An array of nodes
480      */
481     getNodes : function(start, end){
482         var ns = this.nodes;
483         start = start || 0;
484         end = typeof end == "undefined" ? ns.length - 1 : end;
485         var nodes = [];
486         if(start <= end){
487             for(var i = start; i <= end; i++){
488                 nodes.push(ns[i]);
489             }
490         } else{
491             for(var i = start; i >= end; i--){
492                 nodes.push(ns[i]);
493             }
494         }
495         return nodes;
496     },
497
498     /**
499      * Finds the index of the passed node
500      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
501      * @return {Number} The index of the node or -1
502      */
503     indexOf : function(node){
504         node = this.getNode(node);
505         if(typeof node.nodeIndex == "number"){
506             return node.nodeIndex;
507         }
508         var ns = this.nodes;
509         for(var i = 0, len = ns.length; i < len; i++){
510             if(ns[i] == node){
511                 return i;
512             }
513         }
514         return -1;
515     }
516 });