Shyam Ramineni
Shyam Ramineni

Reputation: 51

Backbone.js collection initialization query

I am learing backbone.js and came across interesting scenario.

var EmployeeList = Backbone.Collection.extend({
  url: 'http://localhost:80/employee/employee/employeelist'
});

alert('Collection created');

var employeeList = new EmployeeList();
employeeList.on("reset", function(){
  alert(employeeList.length + " item(s) found");
});
employeeList.fetch();

alert(employeeList.length);

I am not able to understand why the second alert doesn't show length properly.

Upvotes: 0

Views: 90

Answers (1)

jakee
jakee

Reputation: 18556

The alert alert(employeeList.length + " item(s) found") should display the correct length, because it is run after the reset -event is triggered following the populating of the collection.

The alert alert(employeeList.length); right after fetch shouldn't give you consistently the correct result, because collections are fetched asynchronously by default, so the alert is processed right after the AJAX-call for the fetch has been fired and hasn't possibly returned yet.

Timeline is something like this

  1. Fetch triggers ajax call to 'http://localhost:80/employee/employee/employeelist'
  2. alert(employeeList.length); is called, but collection is empty
  3. Fetch returns eventually triggering a reset
  4. alert(employeeList.length + " item(s) found"); is called

Upvotes: 2

Related Questions