Skip to content

Commit 4e83218

Browse files
committed
accept object values in v-class
1 parent 2a56dbb commit 4e83218

File tree

2 files changed

+55
-16
lines changed

2 files changed

+55
-16
lines changed

src/directives/class.js

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,44 @@ var _ = require('../util')
22
var addClass = _.addClass
33
var removeClass = _.removeClass
44

5-
module.exports = function (value) {
6-
if (this.arg) {
7-
var method = value ? addClass : removeClass
8-
method(this.el, this.arg)
9-
} else {
5+
module.exports = {
6+
7+
update: function (value) {
8+
if (this.arg) {
9+
// single toggle
10+
var method = value ? addClass : removeClass
11+
method(this.el, this.arg)
12+
} else {
13+
this.cleanup()
14+
if (value && typeof value === 'string') {
15+
// raw CSSText
16+
addClass(this.el, value)
17+
this.lastVal = value
18+
} else if (_.isPlainObject(value)) {
19+
// object toggle
20+
for (var key in value) {
21+
if (value[key]) {
22+
addClass(this.el, key)
23+
} else {
24+
removeClass(this.el, key)
25+
}
26+
}
27+
this.prevKeys = Object.keys(value)
28+
}
29+
}
30+
},
31+
32+
cleanup: function (value) {
1033
if (this.lastVal) {
1134
removeClass(this.el, this.lastVal)
1235
}
13-
if (value) {
14-
addClass(this.el, value)
15-
this.lastVal = value
36+
if (this.prevKeys) {
37+
var i = this.prevKeys.length
38+
while (i--) {
39+
if (!value || !value[this.prevKeys[i]]) {
40+
removeClass(this.el, this.prevKeys[i])
41+
}
42+
}
1643
}
1744
}
1845
}

test/unit/specs/directives/class_spec.js

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@ if (_.inBrowser) {
1111

1212
it('with className', function () {
1313
el.className = 'haha'
14-
var dir = {
14+
var dir = _.extend({
1515
el: el,
16-
arg: 'test',
17-
update: def
18-
}
16+
arg: 'test'
17+
}, def)
1918
dir.update(true)
2019
expect(el.className).toBe('haha test')
2120
dir.update(false)
@@ -24,10 +23,7 @@ if (_.inBrowser) {
2423

2524
it('without className', function () {
2625
el.className = 'haha'
27-
var dir = {
28-
el: el,
29-
update: def
30-
}
26+
var dir = _.extend({ el: el }, def)
3127
dir.update('test')
3228
expect(el.className).toBe('haha test')
3329
dir.update('what')
@@ -36,5 +32,21 @@ if (_.inBrowser) {
3632
expect(el.className).toBe('haha')
3733
})
3834

35+
it('object value', function () {
36+
el.className = 'hoho'
37+
var dir = _.extend({ el: el }, def)
38+
dir.update({
39+
a: true,
40+
b: false
41+
})
42+
expect(el.className).toBe('hoho a')
43+
dir.update({
44+
b: true
45+
})
46+
expect(el.className).toBe('hoho b')
47+
dir.update(null)
48+
expect(el.className).toBe('hoho')
49+
})
50+
3951
})
4052
}

0 commit comments

Comments
 (0)