Backbone.DeepModel Demo
Normal case
Code
class Person extends Backbone.DeepModel {}
const p = new Person({
name: { first: '', last: '' },
pets: []
})
// Object
p.set('name.first', 'Tom')
p.set('name.last', 'Watson')
console.log(p.get('name')) //=> {first: 'Tom', last: 'Watson'}
console.log(p.get('name.first')) //=> 'Tom'
console.log(p.get('name.last')) //=> 'Watson'
// Array
p.set('pets[0]', {name: 'Mi', kind: 'Cat'})
p.set('pets.1', {name: 'Boo', kind: 'Dog'})
console.log(p.get('pets[0].name')) //=> 'Mi'
console.log(p.get('pets[0].kind')) //=> 'Cat'
console.log(p.get('pets.1')) //=> {name: 'Boo', kind: 'Dog'}
// key-value style
p.set({
'name.first': 'Ken',
'pets[0].name': 'Tama'
})
console.log(p.get('name.first')) //=> 'Ken'
console.log(p.get('pets[0].name')) //=> 'Tama'
Output
Custom Parser
Code
Backbone.DeepModel.defaults({
// JSON Pointer parser (https://tools.ietf.org/html/rfc6901)
pathParser(path) {
if (path.indexOf('/') === -1) {
return [path]
}
if (path.charAt(0) !== '/') {
throw new Error('Invalid JSON pointer: ' + path)
}
return path.substring(1).split('/').map(str =>
str.replace(/~1/g, '/').replace(/~0/g, '~')
)
}
})
const model = new Backbone.DeepModel()
model.set({
'/foo': ['bar', 'baz'],
'/': 0,
'/a~1b': 1,
'/c%d': 2,
'/e^f': 3,
'/g|h': 4,
'/i\\j': 5,
'/k\"l': 6,
'/ ': 7,
'/m~0n': 8
})
console.log(model.toJSON())
Output