Dojo setQuery() on DataGrid - all items disappear? - dojo

I've racked my brain and done tons of research and testing and can't figure out what is going on.
I have a Dojo datagrid which is declared statically with some HTML. Using the GUI, my users will add items to the DataGrid, which works as it should. However, I'd like to have a function that is called at a certain point that uses Dojo's setQuery to filter the data that shows in the DataGrid. The problem is that once I run the setQuery command, ALL of the data in the grid disappears, no matter if it matches the query or not!
Here is some sample code:
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
...
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" queryOptions="{deep:true}" query="{}" rowsPerPage="40"></div>
...
function filterGrid() {
dijit.byId("grid").setQuery({color:"Red"});
}
....
function addItemToGrid(formdata) {
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
}

Managed to fix it by running the a grid FILTER instead of setQuery periodically in the background with the help of some jQuery (not sure if setQuery would have worked as well, I don't really know the difference between the filter and setQuery, but filter is doing what I need it to do).
Here is some sample code; hope this helps someone else having problems with this:
// ADD JQUERY
<script src="http://code.jquery.com/jquery-latest.js"></script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
$(document).ready(function() {
function filterTheDataGrid() {
if (dijit.byId("grid") != undefined) {
dijit.byId("grid").filter({color: "Red"});
}
}
// RUN THE filterTheDataGrid FUNCTION EVERY ONE SECOND (1000 MILLISECONDS) //
// LOWER '1000' FOR FASTER REFRESHING, MAYBE TO 500 FOR EVERY 0.5 SECOND REFRESHES //
var refreshDataGrid = setInterval(function() { filterTheDataGrid(); }, 1000);
}
</script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
// SETUP THE LAYOUT FOR THE DATA //
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
</script>
.
// PUT THIS IN THE <HTML> OF THE PAGE
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" query="{ type: '*' }" clientSort="true" rowsPerPage="40"></div>
.
<script type="text/javascript">
function addItemToGrid(formdata) {
// THIS FUNCTION IS CALLED BY A DIALOG BOX AND GETS FORM DATA PASSED TO IT //
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
}
</script>

Here is another option that I came up with, so that the filter is not running unnecessarily every x milliseconds; this basically uses JavaScript to make a new setInterval which runs once after 500 milliseconds and then does a clearInterval so that it doesn't run again. Looks like just calling the filterTheDataGrids() function after adding an item won't do.. we have to delay for a split second and then call it:
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
// Declare the global variables
var refreshDataGrid;
var refreshDataGridInterval = 500; // Change this as necessary to control how long to wait before refreshing the Data Grids after an item is added or removed.
</script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
function filterTheDataGrids() {
if (dijit.byId("grid") != undefined) {
dijit.byId("grid").filter({color: "Red"});
}
clearInterval (refreshDataGrid); // Running the filter just once should be fine; if the filter runs too quickly, then make the global refreshDataGridInterval variable larger
}
</script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
// SETUP THE LAYOUT FOR THE DATA //
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
</script>
.
// PUT THIS IN THE <HTML> OF THE PAGE
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" query="{ type: '*' }" clientSort="true" rowsPerPage="40"></div>
.
<script type="text/javascript">
function addItemToGrid(formdata) {
// THIS FUNCTION IS CALLED BY A DIALOG BOX AND GETS FORM DATA PASSED TO IT //
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
// Create setInterval on the filterTheDataGrids function; since simple calling the function won't do; seems to call it too fast or something
refreshDataGrid = setInterval(function() { filterTheDataGrids(); }, refreshDataGridInterval);
}
</script>

Related

Creating a custom rally grid from source using app-catalog on github

I saw that Rally made available its custom grid in github, so I downloaded the Rally app-catalog from github. I then went into the src/apps/grid directory and ran 'rally-app-builder build'. That created the deploy directory and the following code in App.html:
<!DOCTYPE html>
<html>
<head>
<title>Custom Grid</title>
<script type="text/javascript" src="/apps/2.0rc2/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function () {
(function(){var Ext=window.Ext4||window.Ext,appAutoScroll=Ext.isIE7||Ext.isIE8,gridAutoScroll=!appAutoScroll;Ext.define("Rally.apps.grid.GridApp",{extend:"Rally.app.App",layout:"fit",requires:["Rally.data.util.Sorter","Rally.data.QueryFilter","Rally.ui.grid.Grid","Rally.ui.grid.plugin.PercentDonePopoverPlugin"],autoScroll:appAutoScroll,launch:function(){Rally.data.ModelFactory.getModel({type:this.getContext().get("objectType"),success:this._createGrid,scope:this})},_getFetchOnlyFields:function(){return["LatestDiscussionAgeInMinutes"]},_createGrid:function(model){var context=this.getContext(),pageSize=context.get("pageSize"),fetch=context.get("fetch"),columns=this._getColumns(fetch),gridConfig={xtype:"rallygrid",model:model,columnCfgs:columns,enableColumnHide:!1,enableRanking:!0,enableBulkEdit:Rally.environment.getContext().isFeatureEnabled("EXT4_GRID_BULK_EDIT"),autoScroll:gridAutoScroll,plugins:this._getPlugins(columns),storeConfig:{fetch:fetch,sorters:Rally.data.util.Sorter.sorters(context.get("order")),context:context.getDataContext(),listeners:{load:this._updateAppContainerSize,scope:this}},pagingToolbarCfg:{pageSizes:[pageSize]}};pageSize&&(pageSize-=0,isNaN(pageSize)||(gridConfig.storeConfig.pageSize=pageSize)),context.get("query")&&(gridConfig.storeConfig.filters=[Rally.data.QueryFilter.fromQueryString(context.get("query"))]),this.add(gridConfig)},_updateAppContainerSize:function(){if(this.appContainer){var grid=this.down("rallygrid");grid.el.setHeight("auto"),grid.body.setHeight("auto"),grid.view.el.setHeight("auto"),this.setSize({height:grid.getHeight()+_.reduce(grid.getDockedItems(),function(acc,item){return acc+item.getHeight()+item.el.getMargin("tb")},0)}),this.appContainer.setPanelHeightToAppHeight()}},_getColumns:function(fetch){return fetch?Ext.Array.difference(fetch.split(","),this._getFetchOnlyFields()):[]},_getPlugins:function(columns){var plugins=[];return Ext.Array.intersect(columns,["PercentDoneByStoryPlanEstimate","PercentDoneByStoryCount"]).length>0&&plugins.push("rallypercentdonepopoverplugin"),plugins}})})();
Rally.launchApp('Rally.apps.grid.GridApp', {
name:"Custom Grid",
parentRepos:""
});
});
</script>
</head>
<body></body>
</html>
...but when you paste that into Rally, it just produces and empty app (frame with no contents).
Am I missing something simple here? Are there some tweaks I need to make to get this to work?
I just remembered I fixed the custom grid up quite a bit after 2.0rc2 was cut. You can see that here in the RallySoftware/app-catalog repo.
(We only guarantee these apps work with the head revision of the sdk (version x) but in this case the grid correctly works with 2.0rc2 as well).
Note: it does not have a settings panel yet.
Below is the full html with some default settings filled in:
<!DOCTYPE html>
<html>
<head>
<title>Custom Grid</title>
<script type="text/javascript" src="/apps/2.0rc2/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function () {
(function () {
var Ext = window.Ext4 || window.Ext;
var appAutoScroll = Ext.isIE7 || Ext.isIE8;
var gridAutoScroll = !appAutoScroll;
Ext.define('Rally.apps.grid.GridApp', {
extend: 'Rally.app.App',
layout: 'fit',
requires: [
'Rally.data.util.Sorter',
'Rally.data.wsapi.Filter',
'Rally.ui.grid.Grid',
'Rally.data.ModelFactory',
'Rally.ui.grid.plugin.PercentDonePopoverPlugin'
],
config: {
defaultSettings: {
types: 'defect',
pageSize: 25,
fetch: 'FormattedID,Name,Priority,Severity'
}
},
autoScroll: appAutoScroll,
launch: function () {
var context = this.getContext(),
pageSize = this.getSetting('pageSize'),
fetch = this.getSetting('fetch'),
columns = this._getColumns(fetch);
this.add({
xtype: 'rallygrid',
columnCfgs: columns,
enableColumnHide: false,
enableRanking: true,
enableBulkEdit: context.isFeatureEnabled("EXT4_GRID_BULK_EDIT"),
autoScroll: gridAutoScroll,
plugins: this._getPlugins(columns),
context: this.getContext(),
storeConfig: {
fetch: fetch,
models: this.getSetting('types').split(','),
filters: this._getFilters(),
pageSize: pageSize,
sorters: Rally.data.util.Sorter.sorters(this.getSetting('order')),
listeners: {
load: this._updateAppContainerSize,
scope: this
}
},
pagingToolbarCfg: {
pageSizes: [pageSize]
}
});
},
onTimeboxScopeChange: function (newTimeboxScope) {
this.callParent(arguments);
this.down('rallygrid').filter(this._getFilters(), true, true);
},
_getFilters: function () {
var filters = [],
query = this.getSetting('query'),
timeboxScope = this.getContext().getTimeboxScope();
if (query) {
try {
query = new Ext.Template(query).apply({
user: Rally.util.Ref.getRelativeUri(this.getContext().getUser())
});
} catch (e) {
}
filters.push(Rally.data.wsapi.Filter.fromQueryString(query));
}
if (timeboxScope && _.every(this.getSetting('types').split(','), this._isSchedulableType, this)) {
filters.push(timeboxScope.getQueryFilter());
}
return filters;
},
_isSchedulableType: function (type) {
return _.contains(['hierarchicalrequirement', 'task', 'defect', 'defectsuite', 'testset'], type.toLowerCase());
},
_getFetchOnlyFields: function () {
return ['LatestDiscussionAgeInMinutes'];
},
_updateAppContainerSize: function () {
if (this.appContainer) {
var grid = this.down('rallygrid');
grid.el.setHeight('auto');
grid.body.setHeight('auto');
grid.view.el.setHeight('auto');
this.setSize({height: grid.getHeight() + _.reduce(grid.getDockedItems(), function (acc, item) {
return acc + item.getHeight() + item.el.getMargin('tb');
}, 0)});
this.appContainer.setPanelHeightToAppHeight();
}
},
_getColumns: function (fetch) {
if (fetch) {
return Ext.Array.difference(fetch.split(','), this._getFetchOnlyFields());
}
return [];
},
_getPlugins: function (columns) {
var plugins = [];
if (Ext.Array.intersect(columns, ['PercentDoneByStoryPlanEstimate', 'PercentDoneByStoryCount']).length > 0) {
plugins.push('rallypercentdonepopoverplugin');
}
return plugins;
}
});
})();
Rally.launchApp('Rally.apps.grid.GridApp', {
name: "Custom Grid"
});
});
</script>
</head>
<body></body>
</html>
Hopefully this gets you by for now. Look for a much improved custom grid app coinciding with the next public sdk release.
You are not missing anything. When we cut the next release it will be working, but right now the app has not been toggled on.
What makes it empty is that type below does not resolve:
Rally.data.ModelFactory.getModel({
type: this.getContext().get('objectType'),
success: this._createGrid,
scope: this
});
unless you hard code it instead, as in type: 'defect' . Unfortunately this is not enough to fix it. The app is not ready to be used yet.

grid.startup() not working for different data in the Dojo data grid

Below I have pasted a function to show the data in the datagrid based on the function call shownames('a'). DataGrid is not refreshing for different characters like shownames('b')...and so on . Or, How do I change the data in the datagrid without destroying the grid completely ?
function shownames(chr) {
require([
"dojox/grid/EnhancedGrid",
"dojo/store/Memory",
"dojo/data/ObjectStore",
"dojo/_base/xhr",
"dojo/domReady!"
], function(DataGrid, Memory, ObjectStore, xhr){
var grid, dataStore;
xhr.get({
url: "http://localhost/xampp/namedb.php?name_idx="+chr,
handleAs: "json"
}).then(function(data){
dataStore = new ObjectStore({ objectStore:new Memory({ data: data.items }) });
if(dijit.byId("namegrid")) {
grid.destroy();
} else {
grid = new dojox.grid.EnhancedGrid({
id: "namegrid",
store: dataStore,
query: { name_id: "*" },
queryOptions: {},
structure: [
{ name: "Name", field: "name", width: "25%" },
{ name: "Actual Meaning", field: "meaning", width: "50%" },
{ name: "name_id", field : "name_id", hidden: true }
]
}, "alphanames");
grid.startup();
}
/*
dojo.connect(grid, "onRowClick", grid, function(evt){
var idx = evt.rowIndex,
item = this.getItem(idx);
// get the ID attr of the selected row
var value = this.store.getValue(item, "country_name");
});
*/
});
});
}
Thanks,
Raja
you should not refresh the grid the way you posted it !
First you need to initialize a grid at startup. So the grid shows you some data. Dont create a grid each time !!!! AFTER that your function has to communicate with the grid by using it's methods !
I constantly use this bulk to refresh the grid:
var grid= // CREATE GRID IN HERE
function yourFunction(id) {
var prepareQuery={};
prepareQuery["name_id"]=id; // Create a query based on id
grid._pending_requests={}; // Stop everything thats loading
grid._setQuery(prepareQuery); // Pass query to the grid
grid._refresh(true); // Refresh grid
}
It may also work with your code, but you may have to do some adaptions.

How do I open links in jQuery server side Datatables through the jQuery ColorBox?

So basically I am using jQuery Datatables server-side functionality with PHP to retrieve a table with details from MySQL as illustrated here
From the HTML side, the following jQuery script (1) references the PHP script that grabs the data from MySQL and (2) then defines the table and customizes the columns in the row details.
My problem is getting the links in the row details to collaborate with ColorBox.
Here is the script I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
memTable = $('#members').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "detailsm.php",
"aoColumns": [
{ "sClass": "center", "bSortable": false },
null,
null,
null,
{ "sClass": "center" },
{ "sClass": "center" },
{ "sClass": "center" },
{ "sClass": "center" },
{ "sClass": "center" }
],
"aaSorting": [[1, 'desc']]
} );
$('#members tbody td img').live( 'click', function () {
var memTr = $(this).parents('tr')[0];
if ( memTable.fnIsOpen(memTr) )
{
/* This row is already open - close it */
this.src = "datatables/details_open.png";
memTable.fnClose( memTr );
}
else
{
/* Open this row */
this.src = "datatables/details_close.png";
memTable.fnOpen( memTr, fnFormatMemberDetails(memTr), 'details' );
}
} );
} );
var memTable;
/* Formating function for row details */
function fnFormatMemberDetails ( memTr )
{
var mData = memTable.fnGetData( memTr );
var smOut = '<table cellpadding="2" cellspacing="0" border="0" style="padding-left:20px;">';
smOut += '<tr><td><b>Member Functions:</b></td><td></td><td><b>Details:</b></td><td></td></tr>';
smOut += '<tr><td><a class="iframesmall" href="changecontact.php?userid='+mData[1]+'&fn=chusr">Update Info</a></td><td><a class="iframe" href="notifymember.php?memberid='+mData[1]+'">Notify</a></td>'
+'<td>Full Name: '+mData[14]+' '+mData[3]+'</td><td>Category: '+mData[11]+' | Created by: '+mData[12]+'</td></tr>';
smOut += '<tr><td><a class="iframe" href="renewmember.php?memberid='+mData[1]+'">Renew Subscription</a></td><td><a class="iframe" href="rp.php?memberid='+mData[1]+'">Reset Password</a></td> <td>Address: '+mData[15]+', '+mData[16] +', '+mData[17]+'</td><td>Mobile: '+mData[18]+'</td></tr>';
smOut += '<tr><td><a class="iframe" href="disactivatemember.php?memberid='+mData[1]+'">Disactivate</a></td><td><a class="iframe" href="deletemember.php?memberid='+mData[1]+'">Delete</a></td> <td>Last Login: '+mData[10]+ '</td><td>Last Updated: '+mData[13]+'</td></tr>';
smOut += '</table>';
return smOut;
}
</script>
My ColorBox jquery script defines the class iframesmall, which is referenced above in the fnFormatMemberDetails function that formats row details for the jquery data table.
Here is the part of the code from fnFormatMemberDetails that formats my row details as you can see above:
smOut += '<tr><td><a class="iframesmall" href="changecontact.php?userid='+mData[1]+'&fn=chusr">Update Info</a></td><td><a class="iframesmall" href="notifymember.php?memberid='+mData[1]+'">Notify</a></td>'
+'<td>Full Name: '+mData[14]+' '+mData[3]+'</td><td>Category: '+mData[11]+' | Created by: '+mData[12]+'</td></tr>';
And here is my jQuery ColorBox script, which works on the same page when called through regular HTML (but not through HTML output via jQuery/javascript):
<link rel="stylesheet" href="colorbox/colorbox.css" />
<script src="colorbox/jquery.colorbox.js"></script>
<script>
$(document).ready(function(){
//Examples of how to assign the ColorBox event to elements
$(".photogall").colorbox({rel:'photogall'});
$(".photothumbs").colorbox({rel:'photothumbs'});
$(".iframesmall").colorbox({iframe:true, width:"800px", height:"80%"});
});
</script>
To sum it up: How do I get ColorBox to work with html links that are generated via jQuery/javascript? All suggestions are welcome. Thank you.
Simply reapply colorbox() after you add the elements dinamicallhy
else
{
/* Open this row */
this.src = "datatables/details_close.png";
//here you add the data
memTable.fnOpen( memTr, fnFormatMemberDetails(memTr), 'details' );
//here you should add colorbox for the newly added elements
$(".iframesmall").colorbox({iframe:true, width:"800px", height:"80%"});
}
How do I get ColorBox to work with html links that are generated via jQuery/javascript?
Assign or re-assign colorbox after you have generated those links.

How to refilter a dojo DataGrid?

I have a DataGrid that I already filtered using grid.filter(query, rerender). If I add another item, after calling save() I see the new item in the grid even though it shouldn't display because of the filter. I'm thinking "ok, I'll just filter it again when the store finishes saving. But after calling grid.filter with the same query all the rows disappear. Any ideas what I might be doing wrong?
Code to filter the grid:
var filterQuery = dijit.byId("filterTextbox").attr("value");
var grid = dijit.byId("grid");
var queryValue = "*";
if(filterQuery != ""){
queryValue += filterQuery + "*";
}
grid.filter({name: queryValue}, true);
Code to add new items to the grid
function addItemToGrid(newItemName){
var newItem = {name: newItemName};
var grid = dijit.byId("grid");
var store = grid.store;
store.addItem(newItem);
store.save();
}
Try to use:
store.newItem(newItem);
instead of store.addItem(newItem);
(addItem is not a standard method to add items into store)
Inside of your addItemToGrid function, try adding an onComplete listener to your save method and sort or filter the grid in the onComplete function
store.save({onComplete: function() {
grid.filter({name: queryValue}, true);
}
});
I had the same problem and only managed to fix it by running the grid filter periodically in the background with the help of some jQuery. Here is some sample code; hope this helps someone else having problems with this.
// ADD JQUERY
<script src="http://code.jquery.com/jquery-latest.js"></script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
$(document).ready(function() {
function filterTheDataGrid() {
if (dijit.byId("grid") != undefined) {
dijit.byId("grid").filter({color: "Red"});
}
}
// RUN THE filterTheDataGrid FUNCTION EVERY ONE SECOND (1000 MILLISECONDS) //
// LOWER '1000' FOR FASTER REFRESHING, MAYBE TO 500 FOR EVERY 0.5 SECOND REFRESHES //
var refreshDataGrid = setInterval(function() { filterTheDataGrid(); }, 1000);
}
</script>
.
// PUT THIS IN THE <HEAD> OF THE PAGE
<script type="text/javascript">
// SETUP THE LAYOUT FOR THE DATA //
var layoutItems = [[
{
field: "id",
name: "ID",
width: '5px',
hidden: true
},
{
field: "color",
name: "Color",
width: '80px'
}
]];
// Create an empty datastore //
var storeData = {
identifier: 'id',
label: 'id',
items: []
}
var store3 = new dojo.data.ItemFileWriteStore( {data : storeData} );
</script>
.
// PUT THIS IN THE <HTML> OF THE PAGE
<div id="grid" dojoType="dojox.grid.DataGrid" jsId="grid5" store="store3" structure="layoutItems" query="{ type: '*' }" clientSort="true" rowsPerPage="40"></div>
.
<script type="text/javascript">
function addItemToGrid(formdata) {
// THIS FUNCTION IS CALLED BY A DIALOG BOX AND GETS FORM DATA PASSED TO IT //
var jsonobj = eval("(" + dojo.toJson(formData, true) + ")");
var myNewItem = {
id: transactionItemID,
color: jsonobj.color
};
// Insert the new item into the store:
store3.newItem(myNewItem);
store3.save({onComplete: savecomplete, onError: saveerror});
}
</script>

dojox.layout.ContentPane

The followig code is inside a tag script in the head of a JSP.
I wanted to emulate this behaviour http://dante.dojotoolkit.org/static/xd/stack-accordion.html. The main differences from that sample are:
1) I use e Tree to navigate contents in the StackContainer;
2) Content are handled by dojoX.Layout.ContenPane beacuse I want to load some JSP I wrote previously.
dojo.addOnLoad(function(){
var store = new dojo.data.ItemFileReadStore({
data:{
identifier: 'id',
label: 'name',
items: [
{ id: '01', name:'Metadata', type:'Area',
children:[
{_reference:'001'},
{_reference:'002'}
]
},
{ id: '001', name:'Insert', type:'action', content:'content1' },
{ id: '002', name:'Delete', type:'action', content:'content2' },
{ id: '02', name:'Class', type:'Area',
children:[
{_reference:'003'}
]
},
{ id: '003', name:'Create', type:'action', content:'content3'}
]
}
});
var treeModel = new dijit.tree.ForestStoreModel({
store: store,
query: {"type": "Area"},
rootId: "root",
childrenAttrs: ["children"],
openOnClick: true
});
var ciccio = new dijit.Tree({
model: treeModel,
showRoot: false
}, "treeOne");
// make the main container:
var bc = new dijit.layout.BorderContainer({
style:"width:1152px; height:600px"
}, "main");
// add the two regions:
var accordion = new dijit.layout.AccordionContainer({
region:"left",
id:"mainAccordion",
style:"width:150px"
}, "accordion").placeAt(bc);
var stack = new dijit.layout.StackContainer({
region:"center"
}, "stack").placeAt(bc);
var accordion1 = new dijit.layout.AccordionPane({
title: "ciao",
content: ciccio
}).placeAt(accordion);
[...]
var content3 = new dojox.layout.ContentPane({
id: "content3",
adjustPaths:true,
renderStyles:true,
executeScripts:true,
href:"./content3.jsp"
}).placeAt(stack);
dojo.connect(ciccio, "onClick", function(item){
if(store.getValue(item, "type")!= 'Area')
{
var boh = store.getValue(item, "content");
var prova = dijit.byId(boh);
stack.selectChild(prova);
}
else{
alert(store.getLabel(item));
}
});
bc.startup(); /*end dojo.AddOnLoad*/)};
Ande here is the full code of the imported JSP (content3.jsp)
<script type="text/javascript" src="./js/filebox/content3.js"></script>
<div dojoType="dijit.layout.BorderContainer" id="container3"
style="width:auto; height:750px; border: 1px solid #9f9f9f;">
<div dojoType="dijit.layout.ContentPane" region="top">
<h2>Ciao!</h2>
<table>
<tr>
<td><label for="filterBox"> Filter: </label></td>
<td><div dojoType="dijit.form.TextBox"
jsId="filterBox"
id="filterBox"/>
</div>
</td>
</tr>
</table>
</div>
<div dojoType="dijit.layout.ContentPane" region="center">
<table dojoType="dojox.grid.DataGrid"
structure= "content3GridLayout"
columnReordering="true"
noDataMessage="No metadata retrieved"
errorMessage="Invalid data retrieved format"
jsId="content3Grid"
id="content3Grid"
style="width:auto; height:99%;">
</table>
</div>
As you can see at the top of this JSP I import a file JS
Here is it:
var content3GridLayout =
[
{name : "ID", field : "idMetadataClass", width : "10%"},
{name : "Name", field : "className", width : "30%"},
{name : "Description", field : "description", width : "60%"}
];
dojo.xhrPost({
url : "./jsonListGenerator",
content: {action:"classList"},
handleAs : "json",
load : function(responseObject) {
var content3GridStore = new dojo.data.ItemFileReadStore({data:responseObject});
content3Grid.setStore(content3GridStore);
return responseObject;
},
error : function(responseObject) {
dojoAlert("Filebox admin","Internal server error");
return responseObject;
}
});
var lastSearchValue = "";
dojo.connect(dijit.byId(filterBox), "onKeyUp", function(el) {
if (el.explicitOriginalTarget.value!=lastSearchValue) {
lastSearchValue = el.explicitOriginalTarget.value;
var my_filter = "strToFilter = {className: \"*"+ lastSearchValue + "*\" }";
eval(my_filter);
content3Grid.setQuery(strToFilter,{ignoreCase:true});
}
});
Everythings works perfectly except DOJO.CONNECT
Infact firebugs warns that filterBox is undefined when dojo.connect tries to connet to de TextBox declared Markup way.
This problem doesn't show if:
1) the TextBox is declared programmaticaly in the JS file
var filterBox = new dijit.form.Textbox({...});
2) the javascript code belonging to the filterBox is placed next the dojotype tag
<div dojoType="dijit.form.TextBox"
jsId="filterBox"
id="filterBox"/>
<script type="dojo/method" event="onKeyUp">
if (el.explicitOriginalTarget.value!=lastSearchValue) {
lastSearchValue = el.explicitOriginalTarget.value;
var my_filter = "strToFilter = {className: \"*"+ lastSearchValue + "*\" }";
eval(my_filter);
content3Grid.setQuery(strToFilter,{ignoreCase:true});
}
</script>
</div>
Do you know the reason why it happens?
Is it a problem of scope?
Thank you in advance!
Teresa
You should wrap your code in content3.js in a dojo.addOnLoad() call, much like you had in the JSP file in (2). You typically won't want to run any Dojo code until Dojo's 'onload' event fires. There are no guarantees that the code loaded by dojo.require will be available to you, as is the case with the cross-domain (xd) loader. The parser itself doesn't run until the document is finished loading, so Javascript executed immediately will not be able to find the widget.
The parser itself doesn't run until the document is finished loading, so Javascript executed immediately will not be able to find the widget
this is the problem. But even if I wrap the code in dojo.addOnLoad() it seams that the parsing of the content3.JSP is made after the evaluation of the script in content3.JS
Darn...
Anyway thank you for you answare, it helped me to understand the problem.