Converts JS objects into their observable equivalents using observ, observ-array and observ-struct. Designed for use with mercury
npm install observify
var observify = require('observify')
var data = observify({
"foo": "bar",
"cats": ["taco", "burrito"],
"object": { key: 'value' },
"age": 82
})
is equivalent to doing:
var array = require('observ-array')
var struct = require('observ-struct')
var value = require('observ')
var data = struct({
"foo": value("bar"),
"cats": array([value("taco"), value("burrito")]),
"object": struct({ key: 'value' }),
"age": value(82)
})
observ-struct
has a blacklist of property names that cannot be used as keys (as they clash with javascript reserved words).
You can pass an options object with a autoRename
property to tell observify to rename these properties.
var observify = require('observify')
var data = observify({
"name":"I'm bad, I'm bad, you know it",
"comment":"I am OK"
}, {
autoRename:'$'
})
console.log(data())
This would print:
{
$name:"I'm bad, I'm bad, you know it",
comment:"I am OK"
}
If autoRename
is true it will default to $
.
By default observify
will use observ-struct
, but if you want to use a different constructor for objects like observ-varhash you can pass it in as an object:
var data = observify({
originalKey: 1
}, {
objectConstructor: require('observ-varhash')
})
// add a key!
data.put('newKey', 2)
// remove a key!
data.delete('newKey')