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');
});
Related
I am new to Angular 2
- My functionality is working fine in fiddle but when I put in the code base I am getting below errors.
app/components/playing-cables/-update.ts(82,12): error TS2339: Property 'options' does not exist on type 'jQuery'.
app/components/playing-cables/-update.ts(99,21): error TS2339: Property 'Default' does not exist on type 'string'.
storedPreferences.Default = {
dropdown.options = function(data, selectedKey) {
Can you tell me how to fix it.
Providing my code below.
Working code http://jsfiddle.net/yk0up9ht/
import {Component, ElementRef, Inject, OnInit,ViewChild} from '#angular/core';
import { sportService } from '../../services/sport.service';
import {playesRightBarMultiTabComponent} from '../playing-sports/playes-right-bar-multi-tab'
import {playerComponent} from '../player/player.component';
import {ProgressCircle} from '../shared/progress/progress-circle';
import {playeService} from '../../services/playeService';
import {playingsportsEvergreen} from '../playing-sports/playe-sports-evergreen';
import {TextDecoder} from 'text-encoding-shim';
import { Router} from '#angular/router';
import {NetworkCarousel} from '../shared/content/network-carousel';
import {KendoGridComponent} from '../grid/grid.component';
import { TranslateService } from '../../translate/translate.service';
//import { ProgressCircle } from '../shared/progress/progress-circle';
#Component({
selector: 'downlinkBulkUpdate',
templateUrl: "./app/components/playing-cables/downlink-bulk-update.html",
})
export class downlinkBulkUpdate {
public dataSourceVal;
public selectedRowsUID = [];
private count: boolean = true;
private selectAll: boolean;
#ViewChild(KendoGridComponent) private gridkendo: KendoGridComponent;
constructor(public elementRef: ElementRef,private router: Router){
}
private kendocommand = {
edit: { createAt: "bottom" },
group: false,
reorder: true,
resize: true,
sort: true,
filter: { mode: "row,menu" },
autoBind: false,
pager: { messages: { display: "Showing {0} to {1} of {2} entries" } },
model: {},
columns: [],
pagesize: 50,
getComponentUrl: "admin/v1/lockedItems",
saveStatus: false,
excelfileUidName: "ViewUnlockExport",
excelFileName: {
fileName: "ViewUnlockExport",
allPages: true
},
change: function (e) {
console.log("kendocommand downlink-bulk-update");
$('tr').find('[type=checkbox]').prop('checked', false);
$('tr.k-state-selected').find('[type=checkbox]').prop('checked', true);
},
searchFields: []
};
ngOnInit() {
$("tr th[data-field='codeLong']").hide();
if ($('input.checkbox_check').prop('checked')) {
//blah blah
alert("checked");
$("tr th[data-field='codeLong']").show();
}
$("#win1").hide();
/*document.getElementById('cars').options[0].text = localStorage.getItem("someVarName") || 'unkonwn';
var dropdown = $('<select>');
alert("I am here dropdownmenu select"); */
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) {
var self = this;
var newOptions = '<option value="Default">Default</option>'; //create one objec to save new options
$.each(data, function(ix, val) {
var selected = (val == selectedKey) ? 'selected="selected"' : '';
if (val != 'Default') {
newOptions += '<option value="' + val + '" ' + selected + '>' + val + '</option>';
}
//data.push(option);
});
self.html(newOptions);
self.change();
}
//var array = ['one', 'two', 'three'];
var array = [];
var storedPreferences = localStorage.getItem('preferences');
storedPreferences = (storedPreferences) ? JSON.parse(storedPreferences) : {};
storedPreferences.Default = {
columns: [0,1,2],
};
for (var storedPreference in storedPreferences) {
array.push(storedPreference);
}
dropdown.options(array, 'Default');
//$('body').append(dropdown);
$('#btnSubmit').on('click', function(ix, val) {
//should clear out the current options
//and replace with the new array
alert("I am here dropdownmenu");
var newArray = ['four', 'five', 'six'];
dropdown.options(newArray, 'Default');
});
$("#open1").click(function() {
alert("I am here");
$("#win1").show().kendoWindow({
width: "300px",
height: "500px",
modal: true,
title: "Window 1"
});
$("#win1").data("kendoWindow").open();
});
$("#clearPrefrence").click(function() {
alert("clearPrefrence");
//localStorage.clear();
//$("#cars option[value=volvo]").remove();
if ($('#cars').val() != 'Default') {
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
delete preferences[$('#cars').val()];
localStorage.setItem('preferences', JSON.stringify(preferences));
$("#cars option:selected").remove();
$("#cars").change();
}
});
$("#win1Submit").click(function() {
var testingMickey = $("#mickey").val();
alert("win1Submit I am here--->" + testingMickey);
//document.getElementById('cars').options[0].text = testingMickey;
var someVarName = testingMickey;
var preferences = localStorage.getItem('preferences');
if (preferences) {
preferences = JSON.parse(preferences);
}
else {
preferences = {};
}
var preference = {
columns: [],
}
$('#rmenu input[type=checkbox]:checked').each(function() {
preference.columns.push($(this).data('index'));
});
preferences[testingMickey] = preference;
localStorage.setItem('preferences', JSON.stringify(preferences));
var getItemsomeVarName1 = localStorage.getItem('preferences');
getItemsomeVarName1 = JSON.parse(getItemsomeVarName1);
var optionArray = [];
for (var key in getItemsomeVarName1) {
optionArray.push(key);
}
alert("getItemsomeVarName1 I am here--->" + getItemsomeVarName1[testingMickey].columns.length);
dropdown.options(optionArray, testingMickey);
$("#win1").data("kendoWindow").close();
});
setGrid();
function toggleColumns() {
$('#rmenu input[type=checkbox]').each(function(index) {
$(this).data('index', index);
$(this).attr('data-index', index);
});
$('#rmenu input[type=checkbox]').change(function() {
var index = $(this).data('index') + 1;
if ($(this).is(':checked')) {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').show();
}
else {
$('.k-grid-header-wrap > table tr th:nth-child(' + index + '),table.k-focusable tr td:nth-child(' + index + ')').hide();
}
});
$('select').change(function() {
$('#rmenu input[type=checkbox]').removeAttr('checked').prop('checked', false);
var preferences = localStorage.getItem('preferences');
preferences = (preferences) ? JSON.parse(preferences) : {};
var columns = [0,1,2];
var key = $(this).val();
if (preferences && preferences[key]) {
columns = preferences[key].columns;
}
for (var a = 0; a < columns.length; a++) {
$('#rmenu input[type=checkbox][data-index=' + a + ']').prop('checked', true).attr('checked', 'checked');
}
$('#rmenu input[type=checkbox]').each(function() {
$(this).change();
});
});
}
toggleColumns();
$('.k-grid-header').on('contextmenu', function(e) {
e.preventDefault();
let menu = document.getElementById("rmenu");
menu.style.top = e.clientY + 'px';
menu.style.left = e.clientX + 'px';
menu.className = "show";
});
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
function setGrid() {
var ds1 = new kendo.data.DataSource({
transport: {
read: {
//using jsfiddle echo service to simulate JSON endpoint
url: "/echo/json/",
dataType: "json",
type: "POST",
data: {
// /echo/json/ echoes the JSON which you pass as an argument
json: JSON.stringify({
"country": [{
"codeLong": "AUT",
"codeShort": "AT",
"name": "Austria"
},
{
"codeLong": "BEL",
"codeShort": "BE",
"name": "Belgium"
},
{
"codeLong": "BGR",
"codeShort": "BG",
"name": "Bulgaria"
}
]
})
}
}
},
schema: {
data: "country",
model: {
fields: {
codeLong: {
type: "string"
},
codeShort: {
type: "string"
},
name: {
type: "string"
}
}
}
}
});
$("#grid1").kendoGrid({
dataSource: ds1,
height: 180,
scrollable: {
virtual: true
},
columns: [{
field: "codeLong",
title: "codeLong"
},
{
field: "codeShort",
title: "codeShort"
},
{
field: "name",
title: "name"
}
]
});
}
alert("downlink-bulk-update");
console.log("downlink-bulk-update");
let that = this;
$(document).ready(function(){
$(".showHideIcon").click(function(){
alert("titleSearchResults");
});
});
this.kendocommand.model = {
id: "isSelected",
fields: {
contextRow: { editable: false },
isSelected: { type: "boolean", editable: true, filterable: false },
moduleName: { type: "string", editable: false },
entityId: { type: "string", filterable: true, editable: false, nullable: false },
entityName: { type: "string", editable: false, nullable: true },
network: { type: "string", editable: false },
entityType: { type: "string", editable: false },
userLocked: { type: "string", editable: false },
additionalComments: { type: "string", editable: false },
checkOutDate: { editable: false }
}
};
this.kendocommand.columns = [
{
field: 'contextRow',
width: 25, locked: true
},
{
field: "isSelected", filterable: false, sortable: false, editable: true, title: "Is Selected",
template: function (container) { return that.checkboxchecker(container, "isSelected") },
width: 30,
headerTemplate: '<span class="displayBlock"><input type="checkbox" id="unlockCheck" /></span>'
},
{
field: "moduleName",
title: "Module Name", filterable: that.gridkendo.getAutoFilterName("contains", "moduleName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function moduleName(options) {
console.log("downlink-bulk-update 2");
return that.gridTemplate(options, "moduleName", false);
},
width: 150
}, {
field: "entityId", title: "ID",
filterable: that.gridkendo.getAutoFilterName("eq", "entityId"),
headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityId(options) {
console.log("ending this.kendocommand.columns");
return that.gridTemplate(options, "entityId", false);
},
width: 90
}, {
field: "entityName", filterable: that.gridkendo.getAutoFilterName("contains", "entityName"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityName(options) {
return that.gridTemplate(options, "entityName", false);
},
title: "Name",
width: 150
}, {
field: "network",
title: "Network",
filterable: that.gridkendo.getAutoFilterName("contains", "network"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function networkName(options) {
return that.gridTemplate(options, "network", false);
},
width: 110
}, {
field: "entityType",
title: "Type", filterable: that.gridkendo.getAutoFilterName("contains", "entityType"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function entityType(options) {
return that.gridTemplate(options, "entityType", false);
},
width: 150
}, {
field: "userLocked",
title: "User Locked", filterable: that.gridkendo.getAutoFilterName("contains", "userLocked"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function userLocked(options) {
return that.gridTemplate(options, "userLocked", false);
},
width: 150
}, {
field: "additionalComments",
title: "Additional Comments bulk", filterable: that.gridkendo.getAutoFilterName("contains", "additionalComments"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function additionalComments(options) {
return that.gridTemplate(options, "additionalComments", false);
},
width: 200
}, {
field: "checkOutDate",
title: "Date Checked Out", filterable: that.gridkendo.getAutoFilterName("contains", "checkOutDate"), headerAttributes: { class: "multiCheckboxFilterEnabled" },
template: function checkOutDate(options) {
return that.gridTemplate(options, "checkOutDate", false);
},
width: 200
}
];
console.log("ending this.kendocommand.columns");
}
private gridTemplate(options: any, fieldName: any, mandatory: any) {
console.log("gridTemplate downlink-bulk-update");
let value = options[fieldName];
if (options[fieldName] == null || options[fieldName] == undefined) {
value = "";
options[fieldName] = " ";
}
options[fieldName + "FilterRowId"] = value;
return value;
}
checkboxchecker(container, fieldName: any): any {
console.log("checkboxchecker downlink-bulk-update");
if ((this.selectedRowsUID.indexOf(container.uid) != -1) || this.selectAll) {
container.isSelected = true;
return '<input type="checkbox" checked="checked" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
} else {
this.count = true;
container.isSelected = false;
return '<input type="checkbox" style="display:block;" class="textAligncenter unlockCheckbox" #= fieldName ? \'checked="checked"\' : "false" #= fieldName/>';
}
}
}
I suppose the 'options' problems occurs here:
var dropdown = $('#cars');
dropdown.options = function(data, selectedKey) ...
Well, this works in JavaScript, but the error the TypeScript compiler gives you is due to static type-checking. dropdown is here a jQuery object, and that type (assuming you're using type definitions for jQuery) does not declare a options property, so assigning to it generates an error. To allow TypeScript to do this, you must typecast to any, so the object behaves like any JavaScript object:
var dropdown: any = $('#cars');
dropdown.options = (...)
In the case of .Default it is the same error: you are declaring storedPreferences as
var storedPreferences = localStorage.getItem(...);
TypeScript knows that localStorage.getItem returns a string, so it considers storedPreferences to be of type string. In TypeScript you cannot change the type of a variable. In fact, it's the kind of thing it has been designed to prevent (as it is common in JavaScript and cause of frequent errors). TypeScript knows that string does not have a Default property and indicates an error.
To avoid this, again, you must declare storedPreferences to be of type any:
let storedPreferences: any = localStorage.getItem(...);
The problem is that you're programming in TypeScript as if it were JavaScript, and that's why you're getting compiler errors. In TypeScript you cannot add new properties to an object of a known type. To do this, you must previously declare the object as any, so TypeScript behaves exactly like JavaScript (though this way you lose TypeScript advantages).
Besides all this, you should avoid using var and use let or const instead.
The code in jsfiddle works, because that is JavaScript code, not TypeScript code.
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
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);
}
});
}
I've got a Kendo Grid and on its DataBound event, I want to add its data source to a Kendo MultiSelect. So, when the data from the grid is loaded, the below function is fired.
Here's what I have tried so far, without success, but from the code you can see what I intend:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource._data;
for (var i = 0; i < places.length; i++) {
var row = instPlaces[i];
var id = row.Id;
var mediumDescription = row.MediumDescription;
alert(id + " - " + mediumDescription);
multiSelect.dataSource.insert(i, { text: mediumDescription, value: id })
}
multiSelect.dataSource.read();
}
The alert properly shows the id and description of all the datagrid's items, so, I'm getting the data from the grid right.
I add them to the multiSelect's datasource, the last line is to refresh it and show the new data, but it doesn't. The multiSelect remains empty.
Try the following:
function addToMultiSelect() {
var multiSelect = $("#multiSelect").data("kendoMultiSelect");
var grid = $("#grid").data("kendoGrid");
var places = grid.dataSource.data();
// Read original data content
var multiData = multiSelect.dataSource.data();
for (var i = 0; i < places.length; i++) {
...
// insert new element into copy of multiselect data
multiData.push({ text: mediumDescription, value: id })
}
// Write back the modified data
multiSelect.dataSource.data(multiData);
}
See the following code example:
$(document).ready(function() {
function addToMultiSelect(e) {
var grid = this;
var data = this.dataSource.data();
var multiData = [];
for (var i = 0; i < data.length; i++) {
multiData.push({ text: data[i].ShipName, value: i });
}
multi.dataSource.data(multiData);
}
var multi = $("#multi").kendoMultiSelect({
dataSource: {
data: [
{ text: "ship 1", value: 1 },
{ text: "ship 2", value: 2 },
{ text: "ship 3", value: 3 },
{ text: "ship 4", value: 4 }
]
},
dataTextField: "text",
dataValueField: "value"
}).data("kendoMultiSelect");
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: addToMultiSelect,
height: 550,
columns: [
"OrderID",
"Freight",
{
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
},
{
field: "ShipName",
title: "Ship Name"
},
{
field: "ShipCity",
title: "Ship City"
}
]
});
});
html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
Ship Names copied from Grid DataSource: <input id="multi"/>
Grid
<div id="grid"></div>
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.