jQuery dataTable not showing data by default - javascript

I have a jquery DataTable as
html page
<div id="content">
</div>
js code
(function ($) {
'use strict';
var module = {
addTable: function () {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
var data = [];
data = this.getData();
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function () {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return arr;
}
};
$(document).ready(function () {
$('#content').append('Loading....');
module.addTable();
});
})(jQuery);
On initial load, it shows an empty table. Data comes after performing some search. How to show the data by default on initial load?

This is due to javascripts asynchronicity. getData() is not finished at the time of the dataTable initialization. You could make some refactoring, so getData invokes addTable as a callback instead.
var module = {
addTable: function (data) {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function (callback) {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return callback(arr);
},
init : function() {
this.getData(this.addTable);
}
};
...
module.init();
init() calls getData(callback) with addTable as param, addTable have had the param data added.
demo -> http://jsfiddle.net/bLzaepok/
I assume your getData code is only per example, and you are using AJAX (or whatever) IRL. Call the callback in the callback :
getData: function (callback) {
$.ajax({
...
success : function(data) {
callback(data);
}
});
}

Related

javascript code not picking up code_description value for first record

I have something similar to the JSFiddle mentioned here. The JSFiddle works fine, however, I am seeing a strange behaviour in my code. The description of very first
cell is always empty even though I am seeing that in the returned data (in JSON format) from the webservice, the description is present for each record. Please
take a look at the code below and let me know if I am missing anything:
this.processEmployees = function (data_, textStatus_, jqXHR_) {
var collection = data_.employees;
// A helper function used for employee codes below.
var isUsedKey = function (arrayOfObject, key) {
for (var i = 0; i < arrayOfObject.length; i += 1) {
if (arrayOfObject[i].key == key) {
return true;
}
}
return false;
};
var employeeCodes = [];
for (var i = 0; i < collection.length; i++) {
if (i == 0) {
var newItem = {};
newItem.key = collection[i].code_value;
newItem.dates = [collection[i].code_assignment_date];
newItem.description = collection[i].code_description;
newItem.hiringCriterion = collection[i].hiring_criteria;
newItem.name = collection[i].name;
console.log("Would like to check code_description for first item:",collection[i].code_description);
//debugger;
employeeCodes.push(newItem);
} else {
var item = collection[i];
var itemName = item.code_value;
var itemDate = item.code_assignment_date;
var itemDescription = item.code_description;
var hiringCriterion = item.hiring_criteria;
var itemCodeName = item.name;
if (isUsedKey(employeeCodes, itemName)) {
for (var j = 0; j < employeeCodes.length; j++) {
if (employeeCodes[j].key == itemName) {
var index = employeeCodes[j].dates.length;
employeeCodes[j].dates[index] = itemDate;
}
}
} else {
var nextNewItem = {};
nextNewItem.key = itemName;
nextNewItem.dates = [itemDate];
nextNewItem.code_description = itemDescription;
nextNewItem.hiring_criteria = hiringCriterion;
nextNewItem.name = itemCodeName;
employeeCodes.push(nextNewItem);
}
}
}
var newSource = {
localdata: employeeCodes,
datafields: [{
name: 'code_value',
type: 'string',
map: 'key'
},
{
name: 'code_assignment_date',
type: 'date',
map: 'dates>0'
},
{
name: 'name',
type: 'string'
},
{
name: 'code_description',
type: 'string'
},
{
name: 'hiring_criteria',
type: 'string'
}
],
datatype: "array"
};
var newAdapter = new $_.jqx.dataAdapter(newSource);
var iconrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
var icon = '';
if (employeeCodes[row].dates.length > 1) {
icon = '<img src="images/icon-down.png" style="position: absolute; right: 5px;" />';
}
return '<span style="position: relative; width: 100%; margin: 4px; float: ' + columnproperties.cellsalign + ';">' + newAdapter.formatDate(value, 'd') + icon + '</span>';
};
$_(self.gridSelector).jqxGrid({
source: newAdapter,
editable: true,
width: '600',
pageable: true,
sortable: true,
autoheight: true,
theme: 'classic',
height: '170',
columnsResize: true,
columns: [
{
text: 'Employee Name',
datafield: 'name',
width: 85,
},
{
text: 'Code Value',
datafield: 'code_value',
width: 75,
editable: false
},
{
text: 'Latest Date(s)',
datafield: 'code_assignment_date',
cellsformat: 'd',
columntype: 'combobox',
width: 100
createeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
console.log("length of info: " + info);
var groupName = info.code_value;
console.log("Contents of groupName: " + groupName);
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({ autoDropDownHeight: false, source: dates, promptText: "Previous Date(s):", scrollBarSize: 10 });
},
initeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
var groupName = info.code_value;
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({
autoDropDownHeight: false,
source: dates,
promptText: "Dates:",
width: 100,
scrollBarSize: 10,
renderer: function (index_, label_, value_) {
return formatDateString(value_);
},
renderSelectedItem: function (index, item) {
var records = editor.jqxComboBox('getItems');
var currentRecord = records[index].label;
return formatDateString(currentRecord);;
}
});
},
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{
text: 'Description',
datafield: 'code_description'
},
{
text: 'Hiring Criterion',
datafield: 'hiring_criteria',
editable: false,
hidden: true
}
],
});
}; // End of processEmployees
For Example, if my JSON is the following:
{
"employees": [{
"code_value": "B1",
"code_assignment_date": "2016-12-13 23:04:00.0",
"code_type": 7,
"code_description": "This employee has received his salary",
"name": "Peter",
"hiring_criteria": null
}, {
"code_value": "A1",
"code_assignment_date": "2016-05-20 05:00:00.0",
"code_type": 7,
"code_description": "Employee has 5 vacation days left",
"name": "Jack",
"hiring_criteria": null
}],
"webServiceStatus": {
"status": "SUCCESS",
"message": "2 results"
}
}
I am not seeing the very first code_description value which is This employee has received his salary in the above JSON response whereas the following
line mentioned in the above code clearly shows it in the console panel:
console.log("Would like to check code_description for first item:",collection[i].code_description);
newItem.description = collection[i].code_description;
---Replace newItem.description to newItem.code_description in First object condition
newItem.hiringCriterion = collection[i].hiring_criteria;
---Replace newItem.hiringCriterion to newItem.hiring_criteria in First object condition

Handsontable Select2 Dynamic Options

I am using handsontable with the select2 editor but I cannot seem to make dynamic options work with the dropdown menu, i.e. the options set at the the time of the handsontable initialisation are the only options that ever seem to show.
I have tried using a global variable as the source of the options and updating that at various points in my code and also using a function to return the same variable but neither attempt seems to work.
e.g.
var hot;
var data = [];
function customDropdownRenderer(instance, td, row, col, prop, value, cellProperties) {
if (instance.getCell(row, col)) {
$(instance.getCell(row,col)).addClass('select2dropdown');
}
var selectedId;
var colOptions = cellProperties.select2Options.data;
if (colOptions != undefined) {
for (var index = 0; index < colOptions.length; index++) {
if (parseInt(value) === colOptions[index].id) {
selectedId = colOptions[index].id;
value = colOptions[index].text;
}
}
Handsontable.TextCell.renderer.apply(this, arguments);
}
}
var requiredText = /([^\s])/;
$(document).ready(function(){
var
$container = $("#example1"),
$parent = $container.parent(),
autosaveNotification;
hot = new Handsontable($container[0], {
columnSorting: true,
stretchH: 'all',
startRows: 8,
startCols: 5,
rowHeaders: true,
colHeaders: ['Description', 'Cost', 'Remarks'],
columns: [
{ data: 'description' },
{
data: 'cost',
editor: 'select2',
renderer: customDropdownRenderer,
select2Options: { data: getData(), dropdownAutoWidth: true }
},
{ data: 'remarks' },
],
minSpareCols: 0,
minSpareRows: 1,
contextMenu: true,
data: []
});
data = [{id:'fixed',text:'Fixed'},{id:'variable',text:'Variable'}];
});
function getData() {
return data;
}
http://jsfiddle.net/zfmdu4wt/27/
You have defined data multiple times and it is causing contention.
The following changes will fix it:
Define the following immediately after the .ready() function:
var source = [{id:'fixed',text:'Fixed'},{id:'variable',text:'Variable'}];
and update the select2Options to the following:
select2Options : { data: source, dropdownAutoWidth: true }
I managed to get it working by re-using some code I had used to solve the same problem with the xeditable plugin.
Here's the updated code:
var hot;
var data = [];
function customDropdownRenderer(instance, td, row, col, prop, value, cellProperties) {
if (instance.getCell(row, col)) {
$(instance.getCell(row,col)).addClass('select2dropdown');
}
var selectedId;
var colOptions = cellProperties.select2Options.data;
if (colOptions != undefined) {
for (var index = 0; index < colOptions.length; index++) {
if (parseInt(value) === colOptions[index].id) {
selectedId = colOptions[index].id;
value = colOptions[index].text;
}
}
Handsontable.TextCell.renderer.apply(this, arguments);
}
}
var requiredText = /([^\s])/;
$(document).ready(function(){
var
$container = $("#example1"),
$parent = $container.parent(),
autosaveNotification;
hot = new Handsontable($container[0], {
columnSorting: true,
stretchH: 'all',
startRows: 8,
startCols: 5,
rowHeaders: true,
colHeaders: ['Description', 'Cost', 'Remarks'],
columns: [
{ data: 'description' },
{
data: 'cost',
editor: 'select2',
renderer: customDropdownRenderer,
// select2Options: { data: getData(), dropdownAutoWidth: true }
select2Options: { data: getSource(), dropdownAutoWidth: true, width: 'resolve', initSelection: getInitSel(false), query: getQuery }
},
{ data: 'remarks' },
],
minSpareCols: 0,
minSpareRows: 1,
contextMenu: true,
data: []
});
data = [{id:'fixed',text:'Fixed'},{id:'variable',text:'Variable'}];
});
/*
function getData() {
return data;
}
*/
// New Code
function getSource() {
return data;
};
function getQuery(options) {
options.callback({ results : getSource() });
};
function getInitSel(multiple) {
return function(el, cb) {
var t, toSet = [], sc = getSource();
el[0].value.split(',').forEach(function(a) {
for (var i = 0; i < sc.length; i++) {
if (sc[i].id == Number(a.trim())) {
t = sc[i];
}
}
// or, if you are using underscore.js
// t = _.findWhere(sc, { id : Number(a.trim()) });
if(t) toSet.push(t);
});
cb(multiple ? toSet : (toSet.length ? toSet[0] : null));
};
};
and a fiddle for demonstration - http://jsfiddle.net/zfmdu4wt/38/

Kendo UI Grid with custom resize event won't display detail template in Internet Explorer

I have a Kendo UI Grid that displays n-child records, that I also have a custom resize function that keeps the grid sized for the browser window height. If I remove that resizeListener, the child records display as appropriate. If I have the resizeListener bound, the child records do not display.
This issue is specific to Internet Explorer 8 (sorry, it's a company policy limitation). The grid functions normally in Firefox.
I have tried using $(window).off("resize") when I activate the child template, in the databound, and in really a variety of random places that I thought might possibly work - but nothing so far.
I'm looking for a solution or a work-around for IE.
Here is the function:
function resizeGrid() {
var gridElement = $("#boxesgrid");
var dataArea = gridElement.find(".k-grid-content");
var newGridHeight = $(document).height() > 850 ? 850 : $(document).height() * .75;
var newDataAreaHeight = newGridHeight * .7;
dataArea.height(newDataAreaHeight);
gridElement.height(newGridHeight);
gridElement.data("kendoGrid").refresh();
}
var resizeListener = function () {
$(window).one("resize", function () {
resizeGrid();
setTimeout(resizeListener, 500);
});
};
Here is the html:
<div class="col-md-2">
<div class="panel panel-default">
<div class="panel-heading">Line of Business</div>
<div class="panel-body" id="lobnav"></div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Application</div>
<div class="panel-body" id="lobapp"></div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Filter</div>
<div class="panel-body" id="jobfilter">
</div>
</div>
</div>
<div class="col-md-10">
<div id="boxesgrid"></div>
</div>
Here is the rest of the javascript/kendo code:
$(document).ready(function () {
resizeListener();
var isParent, appId, lobId, boxId;
var apiUrl = '#ViewBag.ApiUrl';
var lobDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Lob"
}
},
schema: {
model: {
id: "LobId",
hasChildren: "HasChildren"
}
}
});
var appsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "App"
},
parameterMap: function (data, action) {
if (action === "read") {
data.lobid = lobId;
data.parent = isParent;
return data;
} else {
return data;
}
}
}
});
var filterDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Theme"
}
},
schema: {
model: { id: "FilterId" }
}
});
var boxesDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "Process"
},
parameterMap: function (data) {
data.appid = appId;
data.parent = isParent;
data.lobid = lobId;
return kendo.stringify(data);
}
},
schema: {
data: "Data",
total: "Total",
model: { id: "JobId" }
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
});
var lobnav = $("#lobnav").kendoTreeView({
select: function (e) {
var tree = this;
var src = tree.dataItem(e.node);
lobId = src.LobId;
isParent = src.HasChildren;
},
change: function (e) {
appsDataSource.read();
},
dataSource: {
transport: {
read: {
url: apiUrl + "Lob"
}
},
schema: {
model: {
id: "LobId",
hasChildren: "HasChildren"
}
}
},
loadOnDemand: false,
dataTextField: "LobName"
});
var appnav = $("#lobapp").kendoListView({
selectable: "single",
autoBind: false,
change: function () {
var idx = this.select().index();
var itm = this.dataSource.view()[idx];
appId = itm.AppId;
boxesDataSource.query({
page: 1,
pageSize: 35
});
},
template: "<div class='pointercursor'>${AppName}</div>",
dataSource: appsDataSource
});
var jobsfilter = $("#jobfilter").kendoListView({
selectable: "single",
loadOnDemand: false,
template: "<div class='pointercursor' id=${FilterId}>${FilterName}</div>",
dataSource: filterDataSource,
dataBound: function () {
var dsource = $("#jobfilter").data("kendoListView").dataSource;
if (dsource.at(0).FilterName !== "All") {
dsource.insert(0, { FilterId: 0, FilterName: "All" });
}
},
change: function () {
var itm = this.select().index(), dataItem = this.dataSource.view()[itm];
var appDs = appsDataSource.view(), apps = $("#lobapp").data("kendoListView"),
selected = $.map(apps.select(), function (item) {
return appDs[$(item).index()].AppName;
});
if (selected.length > 0) {
if (dataItem.FilterId !== 0) {
var $filter = new Array();
$filter.push({ field: "JobStatusId", operator: "eq", value: dataItem.FilterId });
jgrid.dataSource.filter($filter);
} else {
jgrid.dataSource.filter({});
}
}
}
});
var jgrid = $("#boxesgrid").kendoGrid({
columns: [
{
field: "AppName",
title: "App"
},
{
field: "JobId",
title: "Job Id"
},
{
field: "JobName",
title: "Job Name",
},
{
field: "JobStatus",
title: "Status"
},
{
field: "JobStatusId",
title: "Status Code"
},
{
field: "HasChildren",
title: "Has Children"
},
{
field: "ChildrenCount",
title: "Child Jobs"
}
],
sortable: {
mode: "single",
allowUnsort: true
},
pageable: {
pageSizes: [35],
numeric: true,
refresh: true,
pageSize: 35
},
autoBind: false,
scrollable: true,
resizable: true,
detailInit: detailInit,
dataSource: boxesDataSource
}).data("kendoGrid");
function detailInit(e) {
var eventData = e;
$.ajax({
url: apiUrl + "ProcessJobs",
type: "POST",
data: {BoxId: e.data.JobId, AppId: e.data.AppId},
dataType: "json",
success: function(data, status, xhr) {
initializeDetailGrid(eventData, data);
}
});
};
function initializeDetailGrid(e, result) {
var moreChildren = result[0].HasChildren;
var gridBaseOptions = {
dataSource: result,
scrollable: false,
sortable: true,
columns: [
{
field: "ParentJobId",
title: "Parent Job"
},
{
field: "JobId",
title: "Job Id"
},
{
field: "JobName",
title: "Job Name",
},
{
field: "JobStatus",
title: "Status"
},
{
field: "JobStatusId",
title: "Status Code"
},
{
field: "HasChildren",
title: "Has Children"
},
{
field: "ChildrenCount",
title: "Child Jobs"
}
]
};
var gridOptions = {};
if (moreChildren) {
gridOptions = $.extend({}, gridBaseOptions, { detailInit: detailInit });
} else {
gridOptions = gridBaseOptions;
};
$("<div/>").appendTo(e.detailCell).kendoGrid(gridOptions);
};
});
The resize function needed to be changed. The error was calling refresh on the grid, rather than resize. The corrected function looks like:
function resizeGrid() {
var gridElement = $("#boxesgrid");
var newGridHeight = $(window).height() > 800 ? 800 : $(document).height() * .75;
gridElement.height(newGridHeight);
gridElement.data("kendoGrid").resize();
}
Setting the data area separately was incorrect, as well.

commit changes on existing records in extjs store

my issue is that I want to update existing store and show the changes on the grid.
What I'm doing to update is :
var record = store.getById(me.internalParameters.editInfo.id);
//console.log(me.InfoEditorPanel.hardwareIdField.value);
record.set('hardwareid', me.InfoEditorPanel.hardwareIdField.value);
record.set('location', me.InfoEditorPanel.locationField.value);
record.set('isActive', me.InfoEditorPanel.isActiveField.value);
record.commit();
store.load();
Here what I use to build the grid.
Utils.getPanelListGrid = function (parameters) {
if (parameters.initParameters == null)
parameters.initParameters = {};
var initParameters = parameters.initParameters;
initParameters.gridColumns = [
{ header: "ID", dataIndex: "id", flex: 1 },
{ header: "Hardware ID", dataIndex: "hardwareid", flex: 1 },
{ header: "Location", dataIndex: "location", flex: 1 },
{ header: "Active", dataIndex: "isActive", flex: 1 }
];
return new Backend.shared.MyDataGrid(parameters);
};
Ext.define(
"shared.MyDataGrid", {
extend: "Ext.grid.Panel",
xtype: "MyDataGrid",
title: "MyDataGrid - Hardcoded values",
initParameters: {
storeIdProperty: null,
},
initComponent: function () {
this.store = Ext.create('Ext.data.Store', {
storeId: 'myStore',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'items'
}
},
fields: ['id', 'hardwareid', 'location', 'isActive'],
data: {
'items': [{
'id': '123456',
'hardwareid': "HID-159",
'location': "Bedroom",
'isActive': "No"
}, {
'id': '789456',
'hardwareid': "HID-357",
'location': "Kitchen",
'isActive': "Yes"
}, {
'id': '147852',
'hardwareid': "HID-149",
'location': "Guest-room",
'isActive': "Yes"
}
]
}
});
this.columns = this.initParameters.gridColumns;
this.listeners = {
selectionchange: {
scope: this,
fn: function (selectionModel, selectedRecords, eventOptions) {
this.selectedIds = [];
this.selectedItems = [];
if (selectedRecords != null) {
for (var i = 0; i < selectedRecords.length; i++) {
var item = selectedRecords[i].data;
this.selectedIds.push(item[this.initParameters.storeIdProperty]);
this.selectedItems.push(item)
}
}
if (this.initParameters.selectionChangeCallback != null)
this.initParameters.selectionChangeCallback(this.selectedIds, this.selectedItems);
}
}
};
shared.MyDataGrid.superclass.initComponent.call(this);
},
getRecordCount: function () {
return this.getStore().getTotalCount();
},
getSelectedIds: function () {
return this.selectedIds;
},
getSelectedItems: function () {
return this.selectedItems;
}
});
Can anyone please explain what should I do exactly to make the grid show the updated row?
I suggest that use the following code in your 'selectionchange' event.
this.getStore().load({
params:{
'yourModelIdProperty':'selectedId'
}
});
It's call an store proxy. You should write a function for that proxy and load the updated data.

fetchItemByIdentity() doesn't work as expected

I have an ItemFileWriteStore on my page. When I click any row in my DataGrid I can get the id of that row, but then when I try to do fetchItemByIdentity using that id, it always returns null. Any idea why this could be?
I'm using Dojo 1.5.
function getRemoveFormatter(id) {
return '<img src="/images/icons/delete.png" />';
}
function deleteItem(id) {
console.log(id);
window.grid.store.fetchItemByIdentity({
identity: id,
onItem: function(item, request) { console.log(item); }
});
//window.grid.store.deleteItem(id);
}
dojo.ready(function() {
var store = new dojo.data.ItemFileWriteStore({data:{items:[]}});
window.grid = new dojox.grid.DataGrid({
store: store,
structure: [
{ name: "id", field: "id", width: "50px" },
{ name: "Stylist", field: "stylist", width: "100px" },
{ name: "Service", field: "service", width: "200px" },
{ name: "Length", field: "length", width: "50px" },
{ name: "Remove", field: "remove", width: "30px", formatter: getRemoveFormatter }
],
identifier: "id",
label: "id"});
dojo.byId("services_grid").appendChild(grid.domNode);
grid.startup();
observeAppointmentServiceAddClick(window.grid);
getAppointmentItems();
});
Try making a small change in the way you declare the store and the grid. The identifier and label properties belong in the data section of the store next to items.
var store = new dojo.data.ItemFileWriteStore({data:{
items:[],
identifier: "id",
label: "id"}});
window.grid = new dojox.grid.DataGrid({
store: store,
structure: [
{ name: "id", field: "id", width: "50px" },
{ name: "Stylist", field: "stylist", width: "100px" },
{ name: "Service", field: "service", width: "200px" },
{ name: "Length", field: "length", width: "50px" },
{ name: "Remove", field: "remove", width: "30px", formatter: getRemoveFormatter }
]});
Here is a simpler code and answer on jsfiddle.
http://jsfiddle.net/martlark/UkKXW/1/
<html>
<head><!--dojo stuff--></head>
<body>
<div id='store'></div>
<div id='log'></div>
</body>
</html>
dojo.require("dojo.data.ItemFileWriteStore");
var store = null;
function getItem(id) {
store.fetchItemByIdentity({
identity: id,
onItem: function (item, request) {
var v = store.getValue(item, 'value');
dojo.byId('log').innerHTML = 'getItem(' + id + ') =' + v;
}
});
}
dojo.ready(function () {
var items = [];
for (var p = 0; p < 5; p++) {
items.push({
id: p,
value: 'v ' + p
});
}
store = new dojo.data.ItemFileWriteStore({
data: {
identifier: 'id',
items: items
}
});
var gotList = function (items, request) {
var itemsList = "<ul>";
dojo.forEach(items, function (i) {
itemsList += '<li> id:' + p + ' = ' + store.getValue(i,
"value") + "</li>";
});
itemsList += '</ul>';
dojo.byId('store').innerHTML = itemsList;
}
var gotError = function (error, request) {
alert("The request to the store failed. " + error);
}
// Invoke the search
store.fetch({
onComplete: gotList,
onError: gotError
});
getItem('2');
});

Categories