lively.lang
Version:
JavaScript utils providing useful abstractions for working with collections, functions, objects.
123 lines (81 loc) • 3.24 kB
Markdown
-=-=-=-=-=-=-=-=-=-=-=-=-=-
js object path accessor
-=-=-=-=-=-=-=-=-=-=-=-=-=-
- [Path.prototype](
- [parts](
- [size](
- [slice](
- [isIn](
- [equals](
- [isParentPathOf](
- [relativePathTo](
- [withParentAndKeyDo](
- [set](
- [defineProperty](
- [get](
- [concat](
- [watch](
key names as array
Does the Path resolve to a value when applied to `obj`?
```js
var p1 = Path("foo.1.bar.baz"), p2 = Path(["foo", 1, "bar", "baz"]);
// Path's can be both created via strings or pre-parsed with keys in a list.
p1.equals(p2) // => true
```
```js
var p1 = Path("foo.1.bar.baz"), p2 = Path("foo.1.bar");
p2.isParentPathOf(p1) // => true
p1.isParentPathOf(p2) // => false
```
```js
var p1 = Path("foo.1.bar.baz"), p2 = Path("foo.1");
p2.relativePathTo(p1) // => Path(["bar","baz"])
p1.relativePathTo(p2) // => undefined
```
Deeply resolve path in `obj`, not fully, however, only to the parent
element of the last part of path. Take the parent, the key (the last
part of path) and pass it to `doFunc`. When `ensure` is true, create
objects along path it path does not resolve
#### <a name="Path.prototype-set"></a>Path>>set(obj, val, ensure)
Deeply resolve path in `obj` and set the resulting property to `val`. If
`ensure` is true, create nested structure in between as necessary.
```js
var o1 = {foo: {bar: {baz: 42}}};
var path = Path("foo.bar.baz");
path.set(o1, 43)
o1 // => {foo: {bar: {baz: 43}}}
var o2 = {foo: {}};
path.set(o2, 43, true)
o2 // => {foo: {bar: {baz: 43}}}
```
like `Path>>set`, however uses Objeect.defineProperty
React or be notified on reads or writes to a path in a `target`. Options:
```js
{
target: OBJECT,
uninstall: BOOLEAN,
onGet: FUNCTION,
onSet: FUNCTION,
haltWhenChanged: BOOLEAN,
verbose: BOOLEAN
}
```
```js
// Quite useful for debugging to find out what call-sites change an object.
var o = {foo: {bar: 23}};
Path("foo.bar").watch({target: o, verbose: true});
o.foo.bar = 24; // => You should see: "[object Object].bar changed: 23 -> 24"
```