From 6eeff1960cb18957a177f8a9447b444c05dac2bd Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Mon, 21 Nov 2016 16:36:55 -0500 Subject: [PATCH] add on and fire methods --- compiler/generate/index.js | 24 ++++++++++++++++++++++- test/compiler/events-lifecycle/_config.js | 15 ++++++++++++++ test/compiler/events-lifecycle/main.html | 1 + 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/compiler/events-lifecycle/_config.js create mode 100644 test/compiler/events-lifecycle/main.html diff --git a/compiler/generate/index.js b/compiler/generate/index.js index ec7670c497..57cc64bbec 100644 --- a/compiler/generate/index.js +++ b/compiler/generate/index.js @@ -220,6 +220,8 @@ export default function generate ( parsed, template, options = {} ) { deferred: Object.create( null ) }; + var callbacks = Object.create( null ); + function dispatchObservers ( group, newState, oldState ) { for ( const key in group ) { if ( !( key in newState ) ) continue; @@ -238,6 +240,15 @@ export default function generate ( parsed, template, options = {} ) { } } + this.fire = function fire ( eventName, data ) { + var handlers = eventName in callbacks && callbacks[ eventName ].slice(); + if ( !handlers ) return; + + for ( var i = 0; i < handlers.length; i += 1 ) { + handlers[i].call( this, data ); + } + }; + this.get = function get ( key ) { return state[ key ]; }; @@ -260,13 +271,24 @@ export default function generate ( parsed, template, options = {} ) { }; }; + this.on = function on ( eventName, handler ) { + callbacks[ eventName ] || ( callbacks[ eventName ] = [] ).push( handler ); + + return { + cancel: function () { + const index = callbacks.indexOf( handler ); + if ( ~index ) callbacks.splice( index, 1 ); + } + }; + }; + this.teardown = function teardown () { mainFragment.teardown(); mainFragment = null; state = {}; - ${templateProperties.onteardown ? `template.onteardown.call( this );` : ``} + this.fire( 'teardown' );${templateProperties.onteardown ? `\ntemplate.onteardown.call( this );` : ``} }; let mainFragment = renderMainFragment( this, options.target ); diff --git a/test/compiler/events-lifecycle/_config.js b/test/compiler/events-lifecycle/_config.js new file mode 100644 index 0000000000..24b9a03529 --- /dev/null +++ b/test/compiler/events-lifecycle/_config.js @@ -0,0 +1,15 @@ +import * as assert from 'assert'; + +export default { + test ( component ) { + let count = 0; + + component.on( 'teardown', function () { + assert.equal( this, component ); + count += 1; + }); + + component.teardown(); + assert.equal( count, 1 ); + } +}; diff --git a/test/compiler/events-lifecycle/main.html b/test/compiler/events-lifecycle/main.html new file mode 100644 index 0000000000..7c89b545c5 --- /dev/null +++ b/test/compiler/events-lifecycle/main.html @@ -0,0 +1 @@ +