Created
June 29, 2011 21:49
-
-
Save mrjjwright/1055094 to your computer and use it in GitHub Desktop.
Backbone Sync using dnode
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
| # Overwrite the Backbone sync method to use Dnode and rbdb | |
| Backbone.sync = (method, model, success, error) -> | |
| # Backbone Models have a "hasChanged" function, distinguishing them from Collections | |
| isCollection = if model.hasChanged? then false else true | |
| # Each model has a collection name, the collection in our MongoDB API | |
| collectionName = if isCollection then new (model.model)().collectionName() else model.collectionName() | |
| # A generic response handler using Node style callbacks to invoke Backbone success/error handlers | |
| handleResponse = (err, obj) -> | |
| if err? | |
| if err.message.indexOf("Unauthenticated") != -1 | |
| # Let the app know that the user isn't authenticated | |
| App.publish("NotAuthenticated") | |
| return error(err) | |
| return success(obj) | |
| switch method | |
| when "create" | |
| App.db.insert App.user.toJSON(), collectionName, model.toJSON(), handleResponse | |
| when "read" | |
| findFunct = if isCollection then App.db.find else App.db.findOne | |
| findFunct.call App.db, App.user.toJSON(), collectionName, {}, handleResponse | |
| when "update" | |
| App.db.update App.user.toJSON(), collectionName, model.toJSON(), handleResponse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment