Evan You 12 лет назад
Родитель
Сommit
48e68c10e9
2 измененных файлов с 20 добавлено и 20 удалено
  1. 17 20
      src/compiler.js
  2. 3 0
      test/unit/specs/viewmodel.js

+ 17 - 20
src/compiler.js

@@ -83,11 +83,8 @@ function Compiler (vm, options) {
     // setup observer
     compiler.setupObserver()
 
-    // pre compile / created hook
-    var created = options.beforeCompile || options.created
-    if (created) {
-        created.call(vm, options)
-    }
+    // beforeCompile hook
+    compiler.execHook('beforeCompile', 'created')
 
     // create bindings for things already in scope
     var key, keyPrefix
@@ -125,10 +122,7 @@ function Compiler (vm, options) {
     compiler.init = false
 
     // post compile / ready hook
-    var ready = options.afterCompile || options.ready
-    if (ready) {
-        ready.call(vm, options)
-    }
+    compiler.execHook('afterCompile', 'ready')
 }
 
 var CompilerProto = Compiler.prototype
@@ -549,6 +543,17 @@ CompilerProto.getOption = function (type, id) {
     return (opts[type] && opts[type][id]) || (utils[type] && utils[type][id])
 }
 
+/**
+ *  Execute a user hook
+ */
+CompilerProto.execHook = function (id, alt) {
+    var opts = this.options,
+        hook = opts[id] || opts[alt]
+    if (hook) {
+        hook.call(this.vm, opts)
+    }
+}
+
 /**
  *  Unbind and remove element
  */
@@ -560,14 +565,9 @@ CompilerProto.destroy = function () {
         el          = compiler.el,
         directives  = compiler.dirs,
         exps        = compiler.exps,
-        bindings    = compiler.bindings,
-        beforeDestroy  = compiler.options.beforeDestroy,
-        afterDestroy = compiler.options.afterDestroy
+        bindings    = compiler.bindings
 
-    // call user teardown first
-    if (beforeDestroy) {
-        beforeDestroy.call(vm)
-    }
+    compiler.execHook('beforeDestroy')
 
     // unwatch
     compiler.observer.off()
@@ -621,10 +621,7 @@ CompilerProto.destroy = function () {
         vm.$remove()
     }
 
-    // post teardown hook
-    if (afterDestroy) {
-        afterDestroy.call(vm)
-    }
+    compiler.execHook('afterDestroy')
 }
 
 // Helpers --------------------------------------------------------------------

+ 3 - 0
test/unit/specs/viewmodel.js

@@ -306,6 +306,9 @@ describe('UNIT: ViewModel', function () {
                 $remove: function () {
                     elRemoved = true
                 }
+            },
+            execHook: function (id) {
+                this.options[id].call(this)
             }
         }