id already registered dojo - dojo

I have a TabContainer, to which I m adding ContentPanels. My requirement demands that, I reload this TabContainer(which different content in ContentPanels) everytime, I click a new row on grid(generated from ajax in the same page).
Initially, when I got the problem that id is already registered, I used destroyRecursive, as seen in suggested in one of the answers here.
Now, after using that, I m getting the following result:
Result after I click on any of the row, the first time:
Just like the way, I want, with the container and the 3 content panes.
Result after I click on any of the row, the second time, and any other times:
A new container with 3 content panes is placed on top of the old one with 3 content panes.
No matter, how many rows I click, the result always has 2 containers, with new one placed above the old one.
Below is the code, I have used.
<div id = "tabsContainer">
<div id="tabPanels" data-dojo-type = "dijit/layout/TabContainer"></div>
</div>
function getTabPanelsForTheRow() {
require(["dijit/layout/TabContainer",
"dijit/layout/ContentPane"], function (TabContainer, ContentPane) {
var tc = new TabContainer({}, "tabPanels");
var cp1 = new ContentPane({
title: "Contacts",
content: "These are the activities"
});
tc.addChild(cp1);
var cp2 = new ContentPane({
title: "Activities",
content: "These are the activities"
});
tc.addChild(cp2);
var cp3 = new ContentPane({
title: "Opportunities",
content: "We are known for our drinks."
});
tc.addChild(cp3);
tc.startup();
});
}
function destroyTabPanel() {
require(["dijit/layout/TabContainer"], function (TabContainer) {
var tp = dijit.byId("tabPanels");
tp.destroyRecursive(true);
});
}
Everytime, I click a row, I m calling destroyTabPanel() first, and then I m calling getTabPanelsForTheRow().

Looks to me like your problem is the "true" in your destroyRecursive() call which is instructing dojo to preserve the DOM. So you're destroying the widgets which has solved your duplicate id problem but the generated DOM is preserved; then when you call getTabPanelsForTheRow() it is generating 3 new panels over the existing ones.
What you want to do is, after calling destroyRecursive(), empty the container "tabPanel": domConstruct.empty("tabPanel") before calling getTabPanelsForTheRow().
On a side note, you're destroying and re-instantiating your panel widget everytime you click on a row, why not store a reference to your contentPanes within your TabContainer and then write a method which destroys the contentPanes only, empty the TabContainer node and then create the new panes...

Related

dgrid always showing one record less then present

I am using dgrid as follows:
query_grid: function(json_query, target, select){
var self = this;
require(["dojo/_base/declare",
"dgrid/Grid",
"dgrid/extensions/ColumnResizer",
"dgrid/Selection",
"dgrid/selector",
"dgrid/extensions/DijitRegistry",
"dgrid/extensions/Pagination"],
function(declare, Grid, ColumnResizer, Selection, selector, DijitRegistry, Pagination){
util.destroy("grid_"+json_query.path);
var columns = {};
if (select){
columns.widget = selector({
id: "widget",
label: " ",
selectorType: "radio",
resizeable: false,
width: 30});
}
var data = json_query.data;
for (var i=0; i<data.keys.length; i++){
columns[data.keys[i]] = {label: util.slice_path(data.keys[i], 2)};
}
var grid = new (declare([Grid, ColumnResizer, Selection, DijitRegistry, Pagination]))({
id: "grid_"+json_query.path,
columns: columns,
store: new Memory({data: data.records}),
selectionMode: select?"single":"none",
pagingLinks: 1,
pagingTextBox: true,
firstLastArrows: true
});
dojo.place(grid.domNode, target, 'last');
grid.refresh();
}
);
return json_query.path;
}
but when i look at the result, it always shows one record less then is present, until i click on a column header (resulting in a sort), and then all records are shown. Can anyone expain or help with a solution/workaround?
Replace grid.refresh() with grid.startup().
dgrid will automatically call startup in cases where an instance is in document flow as soon as it's created. That's not the case here since you're placing it afterwards, so you need to call startup after it's in flow to tell it that it can perform geometry-sensitive operations.
Without calling startup, resize is never initially called. As a result, the grid doesn't properly account for the height of the header/footer, and one of your 10 rows is getting obfuscated. It gets fixed when you sort because dgrid/Grid's _setSort method calls resize in case the size of the header row changes due to the placement of the sort arrow.
The reason you can replace refresh with startup in this case is because startup calls refresh anyway.

.dataTable() pagination breaks class .click responsiveness

When I construct a normal table and give each column a distinct class, the classes are responsive for all rows. However, when I call .dataTable() on my table, only page 1 of the paginated results is responsive. Page 2 and beyond are not responsive.
Example code:
var dataTableID = 'questionsTable';
var columns = {
questionID: "ID",
CategoryString: "Cat",
difficultyLevel: "Diff",
timesAsked: "Qty",
questionText: "Question Text"
};
// my own little function that builds the HTML table. <TD> classes are column names
//-- eg .questionID, .CategoryString, etc
var tableHTML = makeTable(questions, columns);
$('#' + dataTableID).html(tableHTML);
// dataTable works nicely except only page 1 .click is responsive!
$('#' + dataTableID).dataTable();
// works fine if I remove .dataTable() above. ONLY works for first page of results
// if I keep .dataTable()
$('.questionID').on("click", function() {
alert('Click called');
});
When using pagination, dataTables change the visible rows by moving <tr>'s back and forth the DOM. $('.questionID').on is processed for columns on the first page only, since those columns is the only visible (accessible) columns after initialization.
So you must assign the click handler (or whatever you want to attach) on page change rather than on initialization. Here by the use of the fnDrawCallback event :
function clickHandler() {
alert('Click called');
}
var dataTable = $('#example').dataTable({
fnDrawCallback : function() {
$('.questionID')
.off("click", clickHandler)
.on("click", clickHandler)
}
});
see demo -> http://jsfiddle.net/U9Jmg/
Notice the use of .off. dataTables actually moves the <tr>'s back and forth the DOM and a table in memory, including any attached events. If previous attached events is not released, we will end up in multiple alerts for each column.
Also note I have only used only one class .questionID for all the columns in the demo. The example is 1.10.x but this works in 1.9.x as well.
As you can see of the comments below, you could also use a delegated event instead of direct event binding. It changes the setup and perhaps it is not suitable for your needs, but anyway :
$('#example tbody').on('click', '.questionID', clickHandler);
see demo -> http://jsfiddle.net/L29Dq/
When using DataTables pagination feature (as you do), only the first page of your data is present in the dom when you attach the click event handler. That's why the handler is attached to the elements on the first page and only to those elements.
When going to another page, DataTables will redraw the table which in effect removes the attached event handler. You have to reattach the event handler after every table draw. The drawCallback option should be the right place for that:
$('#' + dataTableID).dataTable({
"drawCallback": function(settings){
$('.questionID').on("click", function(){
alert('Click called');
});
}
});
As #davidkonrad pointed out in his answer, the click handler should be removed (using off) to avoid handling the event multiple times.
The DataTables page has a section on this as well: Advanced Initialisation - DOM/jQuery events. The example there uses delegated events.

Preload all children for dojo dgrid

So I'm a first time user of dgrid, and I'm currently building my tree grid like this:
var SelectionGrid = new declare([OnDemandGrid, Selection, Keyboard]);
var myGrid = new SelectionGrid({
store: myStore,
selectionMode: "single",
style: {
width: '99%',
height: '99%'
},
columns: columns
});
My problem is, the grid shows metadata for features I'm drawing in openlayers. I've written code in openlayers so that whenever I click on a feature on the map, it fires an event to scroll to that item in the grid and select it. The grid, however, doesn't pre-load the children for each parent, it only fetches the children when the parent row is expanded.
Currently I'm programmatically expanding every row and then reclosing them to force it to fetch, but it's terribly slow and ends up causing browser warnings about javascript taking too long to run, etc.
Is this a side effect of using OnDemandGrid? Is there anyway to just have all the data loaded so it's all available when the grid is rendered?
I had another issue and wanted to post another answer in case anybody has the same problem. When not using the Tree plugin and just using the OnDemandGrid, I couldn't programattically scroll to items in the grid that hadn't been loaded because the element for the row was null.
I found a property that tells the OnDemandGrid the minimum number of items to load from the store, and just set it to the length of my data, so it loads everything at once. I know that defeats the purpose/benefit of the OnDemandGrid, but it's the functionality I need. Here's the code:
var SelectionGrid = new declare([OnDemandGrid, Selection, Keyboard, DijitRegistry]);
var grid = new SelectionGrid({
store: store,
selectionMode: "single",
columns: columns,
minRowsPerPage: data.length,
farOffRemoval: 100000
});
Here's the reference for minRowsPerPage and farOffRemoval:
http://dojofoundation.org/packages/dgrid/tutorials/grids_and_stores/
I wasn't able to preload all my data, but I just discovered the glory of dojo/aspect. Now I find the parent item that needs expanded and I just build some code inside an aspect/after block that gets executed as soon as that row is finished expanding/loading:
aspect.after(grid, "expand", function (target, expand) {
var row = grid.row(id);
console.info("found row: ", row)
grid.bodyNode.scrollTop = row.element.offsetTop;
grid.clearSelection();
grid.select(row);
},
true);
grid.expand(item.id, true);

Dojo/Dijit TitlePane

How do you make a titlePane's height dynamic so that if content is added to the pane after the page has loaded the TitlePane will expand?
It looks like the rich content editor being an iframe that is loaded asynchronously confuses the initial layout.
As #missingno mentioned, the resize function is what you want to look at.
If you execute the following function on your page, you can see that it does correctly resize everything:
//iterate through all widgets
dijit.registry.forEach(function(widget){
//if widget has a resize function, call it
if(widget.resize){
widget.resize()
}
});
The above function iterates through all widgets and resizes all of them. This is probably unneccessary. I think you would only need to call it on each of your layout-related widgets, after the dijit.Editor is initialized.
The easiest way to do this on the actual page would probably to add it to your addOnLoad function. For exampe:
dojo.addOnLoad(function() {
dijit.byId("ContentLetterTemplate").set("href","index2.html");
//perform resize on widgets after they are created and parsed.
dijit.registry.forEach(function(widget){
//if widget has a resize function, call it
if(widget.resize){
widget.resize()
}
});
});
EDIT: Another possible fix to the problem is setting the doLayout property on your Content Panes to false. By default all ContentPane's (including subclasses such as TitlePane and dojox.layout.ContentPane) have this property set to true. This means that the size of the ContentPane is predetermined and static. By setting the doLayout property to false, the size of the ContentPanes will grow organically as the content becomes larger or smaller.
Layout widgets have a .resize() method that you can call to trigger a recalculation. Most of the time you don't need to call it yourself (as shown in the examples in the comments) but in some situations you have no choice.
I've made an example how to load data after the pane is open and build content of pane.
What bothers me is after creating grid, I have to first put it into DOM, and after that into title pane, otherwise title pane won't get proper height. There should be cleaner way to do this.
Check it out: http://jsfiddle.net/keemor/T46tt/2/
dojo.require("dijit.TitlePane");
dojo.require("dojo.store.Memory");
dojo.require("dojo.data.ObjectStore");
dojo.require("dojox.grid.DataGrid");
dojo.ready(function() {
var pane = new dijit.TitlePane({
title: 'Dynamic title pane',
open: false,
toggle: function() {
var self = this;
self.inherited('toggle', arguments);
self._setContent(self.onDownloadStart(), true);
if (!self.open) {
return;
}
var xhr = dojo.xhrGet({
url: '/echo/json/',
load: function(r) {
var someData = [{
id: 1,
name: "One"},
{
id: 2,
name: "Two"}];
var store = dojo.data.ObjectStore({
objectStore: new dojo.store.Memory({
data: someData
})
});
var grid = new dojox.grid.DataGrid({
store: store,
structure: [{
name: "Name",
field: "name",
width: "200px"}],
autoHeight: true
});
//After inserting grid anywhere on page it gets height
//Without this line title pane doesn't resize after inserting grid
dojo.place(grid.domNode, dojo.body());
grid.startup();
self.set('content', grid.domNode);
}
});
}
});
dojo.place(pane.domNode, dojo.body());
pane.toggle();
});​
My solution is to move innerWidget.startup() into the after advice to "toggle".
titlePane.aspect = aspect.after(titlePane, 'toggle', function () {
if (titlePane.open) {
titlePane.grid.startup();
titlePane.aspect.remove();
}
});
See the dojo/aspect reference documentation for more information.

Have a custom tableview, how to give a given row a hidden id# variable?

I have a custom built tableview, where I am building the text in the table row by row. I have a big loop that goes through a set of XML data and builds the row based on an RSS XML feed.
Then I added an event listener to see when somone clicks on one of the rows:
tableview.addEventListener('click',function(e)
{
showrow(theid);
});
My question is, during the building of the row, how do i define theid as a variable associated with that row?
I tried a simple
var theid = item.getElementsByTagName("id").item(0).text;
in my loop, but that does work as its always set to the last item in my loop of XML entries.
Thanks!
As you are creating the TableViewRows in your loop, just add the 'theid' property to it with dot notation
var row = Ti.UI.createTableViewRow();
row.theid = item.getElementsByTagName("id").item(0).text;
row.addEventListener('click', function(e){
alert( e.source.theid );
});
Note: If you are adding additional objects on your TableViewRow (like images, labels, etc) make sure you look at the event propagation in the KitchenSink to make sure that 'e.source' is the tableViewRow and not the UI objects added to the tableViewRow
If you want to add the eventListener to the table (not the row) just check the 'rowData' of the click:
table.addEventListener('click', function(e){
alert( e.rowData.theid );
});
you should add custom variables to your row like
var newRow = Ti.UI.createTableViewRow({
title: 'my new row',
customID: item.getElementsByTagName('id').item(0).text
});
tableViewRow.add(newRow);
if that doesn't work, try this:
var newRow = Ti.UI.createTableViewRow({
title: 'my new row',
'customID': item.getElementsByTagName('id').item(0).text
});
tableViewRow.add(newRow);