Skip to content

Commit 00d423d

Browse files
committed
add $set method for observed objects
1 parent 163882a commit 00d423d

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/observer/object.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,24 @@ _.define(
3434
}
3535
)
3636

37+
/**
38+
* Set a property on an observed object, calling add to
39+
* ensure the property is observed.
40+
*
41+
* @param {String} key
42+
* @param {*} val
43+
* @public
44+
*/
45+
46+
_.define(
47+
objProto,
48+
'$set',
49+
function $set (key, val) {
50+
this.$add(key, val)
51+
this[key] = val
52+
}
53+
)
54+
3755
/**
3856
* Deletes a property from an observed object
3957
* and emits corresponding event

test/unit/specs/observer/observer_spec.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ describe('Observer', function () {
8989
expect(watcher.update.calls.count()).toBe(3)
9090
})
9191

92-
it('observing $add/$delete', function () {
92+
it('observing $add/$set/$delete', function () {
9393
var obj = { a: 1 }
9494
var ob = Observer.create(obj)
9595
var dep = new Dep()
@@ -105,9 +105,18 @@ describe('Observer', function () {
105105
obj.$add('b', 3)
106106
expect(obj.b).toBe(2)
107107
expect(dep.notify.calls.count()).toBe(2)
108+
// set existing key, should be a plain set and not
109+
// trigger own ob's notify
110+
obj.$set('b', 3)
111+
expect(obj.b).toBe(3)
112+
expect(dep.notify.calls.count()).toBe(2)
113+
// set non-existing key
114+
obj.$set('c', 1)
115+
expect(obj.c).toBe(1)
116+
expect(dep.notify.calls.count()).toBe(3)
108117
// should ignore deleting non-existing key
109118
obj.$delete('a')
110-
expect(dep.notify.calls.count()).toBe(2)
119+
expect(dep.notify.calls.count()).toBe(3)
111120
// should work on non-observed objects
112121
var obj2 = { a: 1 }
113122
obj2.$delete('a')

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy