Created
September 9, 2013 17:51
-
-
Save tkh44/6499099 to your computer and use it in GitHub Desktop.
Phonegap contacts as backbone collection store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var PhonegapContactStore = function(){}; | |
| _.extend(PhonegapContactStore.prototype,{ | |
| create: $.noop, | |
| update: $.noop, | |
| find: function(data, cb) { | |
| // If we are not on device with contacts just return callback | |
| if (typeof ContactFindOptions === "undefined") { | |
| if (cb) cb(); | |
| return; | |
| } | |
| var fields = ['name', 'displayName', 'emails'], | |
| options = new ContactFindOptions(), | |
| callback = cb || $.noop, | |
| self = this, | |
| resp = []; | |
| options.filter = data.filter || ''; | |
| options.multiple = data.multiple || false; | |
| var onSuccess = function(contacts) { | |
| var self = this; | |
| resp = _.map(_.filter(contacts, function(contact) { | |
| return contact.emails && contact.emails.length; | |
| }), function(contact) { | |
| var name = contact.name, | |
| email; | |
| email = _.findWhere(contact.emails, {'type': 'work'}) || contact.emails[0]; | |
| return { | |
| firstName: name.givenName || '', | |
| lastName: name.familyName || '', | |
| email: email.value | |
| } | |
| } | |
| ); | |
| callback(resp); | |
| }; | |
| var onError = function(error) { | |
| console.log(error); | |
| callback(error); | |
| }; | |
| navigator.contacts.find(fields, _.bind(onSuccess, this), _.bind(onError, this), options); | |
| }, | |
| findAll: $.noop, | |
| destroy: $.noop | |
| }); | |
| _.extend(Backbone, { | |
| // Override `Backbone.sync` to use delegate to the model or collection's | |
| // *phonegapStore* property, which should be an instance of `Store`. | |
| contactSync: function(method, model, options) { | |
| var store = model.phonegapStore || model.collection.phonegapStore; | |
| if (method === 'read') { | |
| store.find(options.data, function(resp) { | |
| _.isArray(resp) ? options.success(resp) : options.error(resp); | |
| }); | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment