Skip to content

Instantly share code, notes, and snippets.

@ccoenraets
Last active December 16, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccoenraets/5443777 to your computer and use it in GitHub Desktop.
Save ccoenraets/5443777 to your computer and use it in GitHub Desktop.
Data Adapters
var app = {
findByName: function() {
this.store.findByName($('.search-key').val()).done(function(employees) {
var l = employees.length;
var e;
$('.employee-list').empty();
for (var i=0; i<l; i++) {
e = employees[i];
$('.employee-list').append('<li><a href="#employees/' + e.id + '">' + e.firstName + ' ' + e.lastName + '</a></li>');
}
});
},
initialize: function() {
this.store = new MemoryAdapter();
this.store.initialize().done(function() {
console.log("Data store initialized");
});
$('.search-key').on('keyup', $.proxy(this.findByName, this));
}
};
app.initialize();
var JSONPAdapter = function() {
this.initialize = function(data) {
var deferred = $.Deferred();
url = data;
deferred.resolve();
return deferred.promise();
}
this.findById = function(id) {
return $.ajax({url: url + "/" + id, dataType: "jsonp"});
}
this.findByName = function(searchKey) {
return $.ajax({url: url + "?name=" + searchKey, dataType: "jsonp"});
}
var url;
}
var MemoryAdapter = function() {
this.initialize = function() {
// No Initialization required
var deferred = $.Deferred();
deferred.resolve();
return deferred.promise();
}
this.findById = function(id) {
var deferred = $.Deferred();
var employee = null;
var l = employees.length;
for (var i=0; i < l; i++) {
if (employees[i].id === id) {
employee = employees[i];
break;
}
}
deferred.resolve(employee);
return deferred.promise();
}
this.findByName = function(searchKey) {
var deferred = $.Deferred();
var results = employees.filter(function(element) {
var fullName = element.firstName + " " + element.lastName;
return fullName.toLowerCase().indexOf(searchKey.toLowerCase()) > -1;
});
deferred.resolve(results);
return deferred.promise();
}
var employees = [
{"id": 1, "firstName": "James", "lastName": "King", "title": "President and CEO"},
{"id": 2, "firstName": "Julie", "lastName": "Taylor", "title": "VP of Marketing"},
{"id": 3, "firstName": "Eugene", "lastName": "Lee", "title": "CFO"},
{"id": 4, "firstName": "John", "lastName": "Williams", "title": "VP of Engineering"},
{"id": 5, "firstName": "Ray", "lastName": "Moore", "title": "VP of Sales"}
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment