Reputation: 3225
I am fairly new to Vue and JS overall. I am creating custom directive in VUE that will have two event listeners, one to the node of the attached directive and another to tooltip node i dynamically append as follows:
app.directive("xedit", {
mounted(el, binding) {
el.setAttribute("contenteditable", true);
el.addEventListener(
"keydown",
(e) => {
if (e.keyCode !== 13) return;
alert("Parent got triggered");
},
false
);
let tooltip = document.createElement("span");
tooltip.setAttribute("contenteditable", true);
tooltip.innerText = " Tooltip it";
tooltip.addEventListener(
"keydown",
(e) => {
if (e.keyCode !== 13) return;
alert("Tooltip Got triggered");
e.stopPropagation();
},
false
);
el.appendChild(tooltip);
});
My expected behaviour that it should trigger the alert("Tooltip Got triggered") when keydown.enter pressed on the dynamically created SPAN tooltip element...that is atleast what i am able to do when in vanillay JS, however. This doesn't work when put in custom directive in VUE. It seems that the expected bubbling effect doesn't seem to be work there b/c it triggers the parent NODE event alert("Parent got triggered") intead
Any help much appricated on how to get triggered event when pressed keydown on the dynamically appended SPAN element
Upvotes: 0
Views: 65
Reputation: 7739
I don't think the event will reach the inner span, since event propagation and bubbling involves only target's parent and ancestors, not its children.
The only solution I can think of is manually triggering the event on tooltip from parent event handler, like so.
const vXedit = {
mounted: (el) => {
el.setAttribute("contenteditable", true);
el.addEventListener(
"keydown",
(e) => {
if (e.keyCode === 13) {
tooltip.dispatchEvent(new Event("triggerTooltip"))
return
}
alert("Parent got triggered");
},
false
);
let tooltip = document.createElement("span");
tooltip.setAttribute("contenteditable", true);
tooltip.innerText = " Tooltip it";
tooltip.addEventListener(
"triggerTooltip",
(e) => {
alert("Tooltip Got triggered");
e.stopPropagation();
},
false
);
el.appendChild(tooltip);
},
};
Upvotes: 0