Loading Contacts
Learn how to adapt the loading process of the contact list according to the persisted data in Marionette.
We'll cover the following...
Loading our contacts collection
Since our contacts are now persisted, let’s adapt how we load them:
Press + to interact
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
...