From 0788ea602723a2ffb22439c11158eb587a3fc1c1 Mon Sep 17 00:00:00 2001 From: John Cowen Date: Wed, 5 Dec 2018 09:32:34 +0000 Subject: [PATCH] ui: Adds controller lifecycle `reset` hook --- .../app/initializers/controller-lifecycle.js | 23 +++++++++++++++++++ ui-v2/app/mixins/with-listeners.js | 23 +++++++++++++------ 2 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 ui-v2/app/initializers/controller-lifecycle.js diff --git a/ui-v2/app/initializers/controller-lifecycle.js b/ui-v2/app/initializers/controller-lifecycle.js new file mode 100644 index 000000000000..bdfee585b618 --- /dev/null +++ b/ui-v2/app/initializers/controller-lifecycle.js @@ -0,0 +1,23 @@ +import Route from '@ember/routing/route'; +/** + * This initializer is very similar to: + * https://github.com/kellyselden/ember-controller-lifecycle + * + * Why is this included here: + * 1. Make sure lifecycle functions are functions, not just truthy. + * 2. Right now we don't want a setup function (at least until we are definitely decided that we want one) + * This is possibly a very personal opinion so it makes sense to just include this file here. + */ +Route.reopen({ + resetController(controller, exiting, transition) { + this._super(...arguments); + if (typeof controller.reset === 'function') { + controller.reset(exiting); + } + }, +}); +export function initialize() {} + +export default { + initialize, +}; diff --git a/ui-v2/app/mixins/with-listeners.js b/ui-v2/app/mixins/with-listeners.js index a1ef188b8046..4a3ac201960b 100644 --- a/ui-v2/app/mixins/with-listeners.js +++ b/ui-v2/app/mixins/with-listeners.js @@ -1,3 +1,4 @@ +import Controller from '@ember/controller'; import Component from '@ember/component'; import Mixin from '@ember/object/mixin'; import { inject as service } from '@ember/service'; @@ -8,15 +9,23 @@ export default Mixin.create({ init: function() { this._super(...arguments); this._listeners = get(this, 'dom').listeners(); - let method = 'willDestroy'; + let teardown = ['willDestroy']; if (this instanceof Component) { - method = 'willDestroyElement'; + teardown = ['willDestroyElement']; + } else if (this instanceof Controller) { + if (typeof this.reset === 'function') { + teardown.push('reset'); + } } - const destroy = this[method]; - this[method] = function() { - destroy(...arguments); - this.removeListeners(); - }; + teardown.forEach(method => { + const destroy = this[method]; + this[method] = function() { + if (typeof destroy === 'function') { + destroy.apply(this, arguments); + } + this.removeListeners(); + }; + }); }, listen: function(target, event, handler) { return this._listeners.add(...arguments);