From 1d5c85ea9d193a647d4ee78d2b6e0170ddb51139 Mon Sep 17 00:00:00 2001 From: Matt Mo Date: Wed, 29 Jul 2020 12:24:36 -0700 Subject: [PATCH] Added a ref callback so that if the reference property changes we will automatically populate the property with the reference to our element. This is allows resetProperties to be used without losing references to elements. --- src/ignite-template.js | 28 ++++++++++++++++++++++------ src/main-app.js | 4 +++- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/ignite-template.js b/src/ignite-template.js index af7f327..dd45aee 100644 --- a/src/ignite-template.js +++ b/src/ignite-template.js @@ -97,9 +97,8 @@ class IgniteTemplate { */ ref(item) { if (item instanceof IgniteProperty) { - this.refs.push((element) => { - item.value = element; - }); + this.callbacks.push(item.attach((oldValue, newValue) => this.onRefChanged(oldValue, newValue, item))); + this.refs.push((element) => item.value = element); } else { this.refs.push(item); } @@ -136,7 +135,7 @@ class IgniteTemplate { } //Invoke any refs we have - this.refs.forEach((ref) => { ref(this.element); }); + this.refs.forEach((ref) => ref(this.element)); } //Set the classes on this element @@ -201,13 +200,13 @@ class IgniteTemplate { this.children = null; } - //disconnect all callbacks + //Disconnect all callbacks if (this.callbacks) { this.callbacks.forEach((item) => item.disconnect()); this.callbacks = null; } - //remove any refs + //Remove any refs if (this.refs) { this.refs = null; } @@ -270,6 +269,23 @@ class IgniteTemplate { this.properties[propertyName] = newValue; } + + /** + * Called when a ref was changed and we need to update the refs + * value to match this elements reference. + * @param {any} oldValue + * @param {any} newValue + * @param {any} ref + */ + onRefChanged(oldValue, newValue, ref) { + console.log(`Ref changed, oldValue: ${oldValue} newValue: ${newValue}`); + + //Only set the reference value to ourself if it's not our element. + //Otherwise we will get a never ending loop. + if (this.element != newValue) { + ref.value = this.element; + } + } } class div extends IgniteTemplate { diff --git a/src/main-app.js b/src/main-app.js index 7bb3598..0169021 100644 --- a/src/main-app.js +++ b/src/main-app.js @@ -11,7 +11,8 @@ class MainApp extends IgniteElement { return { name: "I'm a boss!", items: ["main1", "main2"], - sheetClass: "test" + sheetClass: "test", + sheet: null }; } @@ -21,6 +22,7 @@ class MainApp extends IgniteElement { new Sheet() .property("name", this.name) .property("items", this.items) + .ref(this.sheet) .class(this.sheetClass) .child(new html(`

Im a child for sheet!

`)) )