error row not found for index at app

i am working on this code

  1. 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;
        }
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top