error row not found for index at app
i am working on this code
if i will click first time table view row it will show the error
but it will show the child row.
2.and if i will click the child row this error will show : undefined is not an object
(evaluating (e.row.sub.length)
why i am getting this error?
code
var win = Ti.UI.createWindow();
var container = Ti.UI.createView({ backgroundColor: "white", layout: "vertical" });
var layout = [{
title: "Parent 1",
isparent: true,
opened: false,
sub: [
{ title: "Child 1" },
{ title: "Child 2" }
]
}, {
title: "Parent 2",
isparent: true,
opened: false,
sub: [
{ title: "Child 3" },
{ title: "Child 4" }
]
}];
var tableView = Ti.UI.createTableView({
style: Titanium.UI.iPhone.TableViewStyle.GROUPED,
top: 0,
height: Ti.Platform.displayCaps.platformHeight,
data: layout
});
tableView.addEventListener("click", function (e) {
var i;
//Is this a parent cell?
console.log(e.row);
if (e.row.isparent) {
//Is it opened?
if (e.row.opened) {
for (i = e.row.sub.length; i > 0; i = i - 1) {
tableView.deleteRow(e.index + i);
}
e.row.opened = false;
} else {
//Add teh children.
var currentIndex = e.index;
for (i = 0; i < e.row.sub.length; i++) {
tableView.insertRowAfter(currentIndex, e.row.sub[i]);
currentIndex++;
}
e.row.opened = true;
}
}
});
container.add(tableView);
win.add(container);
win.open();
Any help would be appreciated
Problem with your code is that you are trying to insert many rows at the end of the table when table index wasn't updated yet. The solution for it is to add rows in reverse order using same index.
Here is modified version of your event listener:
tableView.addEventListener("click", function (e) {
var i, rows;
//Is this a parent cell?
if (e.row.isparent) {
//Is it opened?
if (e.row.opened) {
for (i = e.row.sub.length; i > 0; i = i - 1) {
tableView.deleteRow(e.index + i);
}
e.row.opened = false;
} else {
//Add teh children.
rows = e.row.sub.reverse();
for (i = 0; i < rows.length; i++) {
tableView.insertRowAfter(e.index, rows[i]);
}
e.row.opened = true;
}
}
});
Related
I really think I'm going crazy here. So I made a shopping-type app, add to cart and etc.
I have extra comments on each Item which the user can enter any text they want to. The state is correct on "onChangeText" of the input, I checked it with the console. However, when I want to save it (after an edit of the cart), despite the console.log's making sense and that showing the correct state etc, the options changes successfully, but the comments does not. This is very weird as all the other cart array object do change, except the comment. Here is the code:
saveItemCart() {
var index = this.state.cartItems.indexOf(x => x.date === this.state.dateAdded);
let cartItemsArray = this.state.cartItems;
temp = { 'catNumber': this.state.catNumber, 'itemNumber': this.state.itemNumber, 'quantity': this.state.itemQuantity, 'options': this.state.selectedOptions, 'date': this.state.dateAdded, 'comments': this.state.commentsText};
cartItemsArray[index] = temp;
this.setState({ cartItems: cartItemsArray }, () => {
this.updateTotal();
this.setState({ selectedOptions: [], checked: [] })
})
}
State:
state = {
ModalItemShown: false,
ModalCartShown: false,
ModalEditShown: false,
isShowToast: false,
isShowToastError: false,
rest_id: this.props.route.params['restaurantid'],
menuData: this.getMenu(),
catNumber: 1,
itemNumber: 1,
dateAdded: null,
commentsText: "",
cartItems: [],
checked: [],
selectedOptions: [],
total: 0,
itemQuantity: 1,
}
Input (inside the render):
<View style={styles.modalOptions}>
<Input placeholder="..." placeholderTextColor="gray" defaultValue={this.state.commentsText} onChangeText={text => this.setState({ commentsText: text }, () => {console.log(this.state.commentsText)})} />
</View>
<Button shadowless style={styles.button1} color="warning" onPress={() => {
let my = this;
this.showToast(true);
setTimeout(function () { my.showToast(false) }, 1000);
this.saveItemCart();
this.hideModalEdit(false);
}}
>Save</Button>
The problem is in the input of the EDIT cart modal(i.e. page). If the user puts the comment initially before adding it to his cart, then when he opens the edit modal it has the correct comment. If I change it in the edit and click save, and check again, it does not work.
updateTotal:
updateTotal() {
var cartArrayLen = this.state.cartItems.length;
var i;
var j;
var total = 0;
var cart = this.state.cartItems;
for (i = 0; i < cartArrayLen; i++) {
var catNum = cart[i]["catNumber"];
var itemNum = cart[i]["itemNumber"];
var q = cart[i]["quantity"];
var itemPrice = this.state.menuData[catNum - 1][catNum.toString()]["itemsarray"][itemNum]["price"];
itemPrice = Number(itemPrice.replace(/[^0-9.-]+/g, ""));
total = total + (itemPrice * q);
var allItemOptions = this.state.menuData[catNum - 1][catNum.toString()]["itemsarray"][itemNum].options;
var k;
for (k = 0; k < cart[i].options.length; k++) {
var title = cart[i].options[k]["title"];
var index_onmenu = allItemOptions.findIndex(x => x.title === title);
var option_price;
if (Array.isArray(cart[i].options[k].indexes)) {
for (j = 0; j < cart[i].options[k].indexes.length; j++) {
var price_index = cart[i].options[k].indexes[j];
option_price = allItemOptions[index_onmenu].price[price_index]
total = total + Number(option_price) * q
}
} else {
j = cart[i].options[k].indexes
option_price = allItemOptions[index_onmenu].price[j]
total = total + Number(option_price) * q
}
}
};
console.log("New Total: " + total);
this.setState({ total: total }, () => {
this.setState({ itemQuantity: 1 })
})
}
I don't see where you defined the temp variable, but assuming that it is defined somewhere, I think the problem is in how you are updating the cartItems array. Let me explain it by adding some comments in your code:
saveItemCart() {
var index = this.state.cartItems.indexOf(x => x.date === this.state.dateAdded);
let cartItemsArray = this.state.cartItems; // --> Here you are just copying the array reference from the state
temp = { 'catNumber': this.state.catNumber, 'itemNumber': this.state.itemNumber, 'quantity': this.state.itemQuantity, 'options': this.state.selectedOptions, 'date': this.state.dateAdded, 'comments': this.state.commentsText};
cartItemsArray[index] = temp;
this.setState({ cartItems: cartItemsArray }, () => { // --> then you just updated the content of the array keeping the same reference
this.updateTotal();
this.setState({ selectedOptions: [], checked: [] })
})
}
Try doing creating a new array, so the react shallow comparison algorithm can track the state change, like this:
this.setState({ cartItems: Array.from(cartItemsArray) }, /* your callback */);
or
this.setState({ cartItems: [...cartItemsArray]}, /* your callback */);
Hope it helps!
In my project I use ng2-charts. All works fine and chart is shown as expected (data, labels, chart's colors), but when data is changed then color of chart become grey by default. May someone help to correct problem with chart's color?
Here is my code:
import { ChartDataSets } from 'chart.js';
import { Color, Label } from 'ng2-charts';
...
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[];
lineChartLabels: Label[];
lineChartLegend = true;
lineChartType = 'line';
lineChartColors: Color[] = [
{
backgroundColor: 'rgba(148,159,177,0.2)',
borderColor: 'rgba(148,159,177,1)'
},
{
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)'
}];
options: any = {
legend: { position: 'bottom' }
}
constructor(
...//inject services
) {
super();
this.initData();
};
initData(): void {
this.lineChartData = [];
this.lineChartLabels = [];
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
this.isLoading = true;
var limitPromise = this.juridicalLimitService.getPrimary(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
var analyticsPromise = this.juridicalAnalyticsService.getUsedEnergy(this.cabinetId, year).catch(error => {
this.notificationService.error(error);
return Observable.throw(error);
});
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels = data[1].map(e => e.Period);
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Bid'
},
{
data: data[1].map(e => e.Used),
label: 'Used'
}
);
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
export abstract class BidComponent {
cabinetId: number;
isLoading: boolean = false;
#Input("periods") periods: BaseDictionary[];
#Input("cabinetId") set CabinetId(cabinetId: number) {
this.cabinetId = cabinetId;
this.initData();
}
abstract initData(): void;
}
As you can see this component is partial and I use setter to listen of cabinetId changes.
Here is html part:
...
<canvas baseChart width="400" height="150"
[options]="options"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[legend]="lineChartLegend"
[chartType]="lineChartType"
[colors]="lineChartColors"></canvas>
...
And I use this component as:
<app-juridical-bid-primary [cabinetId]="cabinetId"></app-juridical-bid-primary>
I find similar question similar question, but, unfortunately, don't understand answer
After some hours of code testing I find answer. It is needed to correct code from question:
...
import * as _ from 'lodash'; //-- useful library
export class JuridicalBidPrimaryComponent extends BidComponent {
lineChartData: ChartDataSets[] = [];
lineChartLabels: Label[] = [];
...
initData(): void {
/*this.lineChartData = [];
this.lineChartLabels = [];*/ //-- this lines is needed to remove
if (this.cabinetId)
this.getData(this.year);
}
getData(year: number) {
...
forkJoin([limitPromise, analyticsPromise]).subscribe(data => {
this.limits = data[0];
this.lineChartLabels.length = 0;
this.lineChartLabels.push(...data[1].map(e => e.Period));
if (_.isEmpty(this.lineChartData)) {
//-- If data array is empty, then we add data series
this.lineChartData.push(
{
data: data[1].map(e => e.Limit),
label: 'Замовлені величини'
},
{
data: data[1].map(e => e.Used),
label: 'Використано'
}
);
} else {
//-- If we have already added data series then we only change data in data series
this.lineChartData[0].data = data[1].map(e => e.Limit);
this.lineChartData[1].data = data[1].map(e => e.Used);
}
this.isLoading = false;
}, error => {
this.isLoading = false;
});
}
}
As I understand ng2-charts, if we clean dataset (lineChartData) and add new data then the library understand this as create new series and don't use primary settings for the ones. So we have to use previous created series.
I hope it will be useful for anyone who will have such problem as I have.
I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}
Hi everyone I am new using highcharts, I have my data structure and when I try to show, I don't see anything
function nueva (current_data){
var seriesOptions = [],
seriesCounter = 0,
type = ['jobs_running', 'jobs_pending'];
function createChart() {
$('#containerChart').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
for (var j = 0; j < current_data['names'].length; j++){
var all_element = []
name_project = current_data['names'][j];
for (var i = 0; i < type.length; i++){
seriesCounter = 0;
for (var i = 0; i < type.length; i++){
seriesOptions[j] = {
name: type[i],
data: current_data[name_project][type[i]],
};
}
}
createChart();
}
}
I pass current_data to my function that is like this
I want to show 'jobs_running' and 'jobs_pendding' I set the value to seriesOptions
and my array of data has this
Any idea why I don't see anything in the chart! I am missing something.
Thanks in advance
Hopefully you can find your answer in this:
https://jsfiddle.net/ekekp8rh/1/
Not sure what you were hoping to get but at least this displays a chart.
var data = {
projects: [{
name: 'Project X',
jobs_running: [
[1459814400000, 121],
[1459900800000, 205],
[1459987200000, 155],
[1460073600000, 458]
],
jobs_pending: [
[1459814400000, 146],
[1459900800000, 149],
[1459987200000, 158],
[1460073600000, 184]
]
}, {
name: 'Project Y',
jobs_running: [
[1459814400000, 221],
[1459900800000, 295],
[1459987200000, 255],
[1460073600000, 258]
],
jobs_pending: [
[1459814400000, 246],
[1459900800000, 249],
[1459987200000, 258],
[1460073600000, 284]
]
}]
};
nueva(data);
function nueva(current_data) {
var seriesOptions = [],
type = ['jobs_running', 'jobs_pending'];
for (var j = 0; j < current_data['projects'].length; j++) {
var project = current_data['projects'][j];
for (var i = 0; i < type.length; i++) {
seriesOptions.push({
name: project.name + ' ' + type[i],
data: project[type[i]]
});
}
}
$('#containerChart').highcharts('StockChart', {
series: seriesOptions
});
}
I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}