/
contact.js
90 lines (81 loc) · 2.44 KB
/
contact.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
ContactManager.module("Entities", function(Entities, ContactManager, Backbone, Marionette, $, _){
Entities.Contact = Backbone.Model.extend({
urlRoot: "contacts",
validate: function(attrs, options) {
var errors = {}
if (! attrs.firstName) {
errors.firstName = "can't be blank";
}
if (! attrs.lastName) {
errors.lastName = "can't be blank";
}
else{
if (attrs.lastName.length < 2) {
errors.lastName = "is too short";
}
}
if( ! _.isEmpty(errors)){
return errors;
}
}
});
Entities.configureStorage(Entities.Contact);
Entities.ContactCollection = Backbone.Collection.extend({
url: "contacts",
model: Entities.Contact,
comparator: "firstName"
});
Entities.configureStorage(Entities.ContactCollection);
var initializeContacts = function(){
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.models;
};
var API = {
getContactEntities: function(){
var contacts = new Entities.ContactCollection();
var defer = $.Deferred();
contacts.fetch({
success: function(data){
defer.resolve(data);
}
});
var promise = defer.promise();
$.when(promise).done(function(contacts){
if(contacts.length === 0){
// if we don't have any contacts yet, create some for convenience
var models = initializeContacts();
contacts.reset(models);
}
});
return promise;
},
getContactEntity: function(contactId){
var contact = new Entities.Contact({id: contactId});
var defer = $.Deferred();
setTimeout(function(){
contact.fetch({
success: function(data){
defer.resolve(data);
},
error: function(data){
defer.resolve(undefined);
}
});
}, 2000);
return defer.promise();
}
};
ContactManager.reqres.setHandler("contact:entities", function(){
return API.getContactEntities();
});
ContactManager.reqres.setHandler("contact:entity", function(id){
return API.getContactEntity(id);
});
});