Search⌘ K
AI Features

Loading Contacts

Explore how to load and manage persisted contacts in Marionette.js by fetching collections from local storage, initializing default contacts if none exist, and handling requests to load individual contacts. This lesson helps you understand data persistence and retrieval mechanisms within a Backbone and Marionette application.

Loading our contacts collection

Since our contacts are now persisted, let’s adapt how we load them:

Node.js
getContactEntities: function(){
var contacts = new Entities.ContactCollection();
contacts.fetch();
return contacts;
}

Backbone knows where the contacts are stored via the url property, so all we have to do is to fetch them. Of course, we don’t have any persisted contacts right now, and we don’t have a way to create them either. So, let’s cheat by initializing a few contacts if our collection is empty when we load it. Click the “Run” button to see the output:

var initializeContacts = function(){
  var contacts = new Entities.ContactCollection([
      { id: 1, firstName: "Alice", lastName: "Arten",
      phoneNumber: "555-0184" },
      { id: 2, firstName: "Bob", lastName: "Brigham",
      phoneNumber: "555-0163" },
      {id: 3, firstName: "Charlie", lastName: "Campbell",
      phoneNumber: "555-0129" }
  ]);
  contacts.forEach(function(contact){
      contact.save();
  });
  return contacts;
};

var API={
  getContactEntities: function(){
    var contacts = new Entities.ContactCollection();
    contacts.fetch();
    if(contacts.length === 0){
      // if we don't have any contacts yet, create some for convenience
      return initializeContacts();
    }
    return contacts;
  }
};
Initializing contacts for loading
...