0

I am trying to sort an array using an onclick function, and I'm getting the error obj is not defined. Maybe it's not within the scope?

js file:

function pageLoad() {
    var url = API_URL + "/api/Ticket/GetTickets";
    var data = Ajax.getData(url);
    var obj = [];
    var tickets = JSON.parse(data.JsonResult);
    obj.Tickets = tickets;
    Tickets.Data = obj;

    var viewModel = {
        theObject: [obj.Tickets]
    };
    ko.applyBindings(viewModel);
}
function SortColumn(column) {
    obj.Tickets.column.sort();
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137

2 Answers2

1

Yes, it is a scoping issue. Move your obj declaration outside the functions, that way it will be visible to both.

Something like this:

var obj = []; // <-- move here
function pageLoad() {
    var url = API_URL + "/api/Ticket/GetTickets";
    var data = Ajax.getData(url);
    var tickets = JSON.parse(data.JsonResult);
    obj.Tickets = tickets;
    Tickets.Data = obj;

    var viewModel = {
        theObject: [obj.Tickets]
    };
    ko.applyBindings(viewModel);
}
function SortColumn(column) {
    obj.Tickets.column.sort();
}

EDIT:

I'm not sure if you're aware, but [] is shorthand for an Array. If what you're trying to create is an Object, then you should change your assignment to var obj = {};

smaili
  • 1,245
  • 9
  • 18
0

Of course obj is not within scope. It's not in global scope and you aren't passing it into the function.
you can use @smaili's answer as a fix or you can pass obj to the function.

function sortColumn(obj, column) {
    obj.Tickets.column.sort();
    return obj;
}

Then you'll call it with both arguments.

var sortedObj = sortColumn(obj, column);

Further explanation of scoping in Javascript

Community
  • 1
  • 1
Iro
  • 36
  • 3
  • the call to the function is on the aspx page and I don't know if the variable exists over there –  Apr 23 '16 at 20:18
  • @Jennifer okay. It'll still help to really understand scoping because another function could 'corrupt' variables declared in global scope. – Iro Apr 23 '16 at 20:24