Created
August 15, 2017 09:54
-
-
Save samuelantonioli/a52af42055a0acc2c8c3a1064c435be0 to your computer and use it in GitHub Desktop.
Use Backbone.Model / Parse.Object with Vue.js or React
This file contains 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
/** | |
* in models.js (example) | |
**/ | |
import setup_object from './utils/setup_object' | |
var Model = Backbone.Model.extend({ | |
constructor: function() { | |
setup_object(this); | |
Backbone.Model.apply(this, arguments); | |
}, | |
}); | |
export const DocumentModel = Model.extend({ | |
some_method: function() { | |
// ... | |
}, | |
}); |
This file contains 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
/** | |
* We have the following problem: | |
* Backbone.Model uses obj.set(key,val) and obj.get(key) | |
* and you can't use obj.key = val to set values. | |
* | |
* The proxy below can be seen as syntactic sugar, but | |
* some frameworks like react and vue.js work with | |
* POJOs and expect the data to be directly accessible | |
* so this essentially makes it possible to use | |
* Backbone.Model seamlessly with them | |
* (getter/setter, two-way data binding in vue) | |
**/ | |
function setup_object(obj) { | |
var handler = { | |
get: function(data, key) { | |
return obj.get(key); | |
}, | |
set: function(data, key, val, recv) { | |
return obj.set(key, val); | |
}, | |
} | |
var proxy = new Proxy({}, handler); | |
obj.data = proxy; | |
} |
This file contains 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
import {DocumentModel} from './models' | |
var doc = new DocumentModel(); | |
// doc.data is now a proxy which calls doc.set and doc.get | |
// set: | |
doc.data.some_key = 'test'; | |
// get: | |
console.log(doc.data.some_key); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment