Browse Source

fix dynamic attribute on custom directive

kazuya kawaguchi 10 years ago
parent
commit
685519859d
2 changed files with 40 additions and 9 deletions
  1. 6 6
      src/directive.js
  2. 34 3
      test/unit/specs/directive_spec.js

+ 6 - 6
src/directive.js

@@ -156,15 +156,15 @@ Directive.prototype._setupParams = function () {
   while (i--) {
     key = params[i]
     mappedKey = _.camelize(key)
-    val = _.attr(this.el, key)
+    val = _.getBindAttr(this.el, key)
     if (val != null) {
-      // static
-      this.params[mappedKey] = val === '' ? true : val
-    } else {
       // dynamic
-      val = _.getBindAttr(this.el, key)
+      this._setupParamWatcher(mappedKey, val)
+    } else {
+      // static
+      val = _.attr(this.el, key)
       if (val != null) {
-        this._setupParamWatcher(mappedKey, val)
+        this.params[mappedKey] = val === '' ? true : val
       }
     }
   }

+ 34 - 3
test/unit/specs/directive_spec.js

@@ -4,11 +4,14 @@ var nextTick = Vue.nextTick
 
 describe('Directive', function () {
 
-  var el = {} // simply a mock to be able to run in Node
-  var vm, def
-
+  var el, vm, def
   beforeEach(function () {
+    el = document.createElement('div')
     def = {
+      params: ['foo'],
+      paramWatchers: {
+        foo: jasmine.createSpy('foo')
+      },
       bind: jasmine.createSpy('bind'),
       update: jasmine.createSpy('update'),
       unbind: jasmine.createSpy('unbind')
@@ -154,4 +157,32 @@ describe('Directive', function () {
     expect(d.update).toBe(def.update)
     expect(def.update).toHaveBeenCalled()
   })
+
+  it('static params', function () {
+    el.setAttribute('foo', 'hello')
+    var d = new Directive({
+      name: 'test',
+      def: def,
+      expression: 'a'
+    }, vm, el)
+    d._bind()
+    expect(d.params.foo).toBe('hello')
+  })
+
+  it('dynamic params', function (done) {
+    el.setAttribute(':foo', 'a')
+    var d = new Directive({
+      name: 'test',
+      def: def,
+      expression: 'a'
+    }, vm, el)
+    d._bind()
+    expect(d.params.foo).toBe(vm.a)
+    vm.a = 2
+    nextTick(function () {
+      expect(def.paramWatchers.foo).toHaveBeenCalledWith(2, 1)
+      expect(d.params.foo).toBe(vm.a)
+      done()
+    })
+  })
 })