Skip to content

Commit

Permalink
Add monkey patch
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed May 10, 2023
1 parent 8c9786d commit f9e4473
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/morph/src/morph.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ let resolveStep = () => {}
let logger = () => {}

export function morph(from, toHtml, options) {
monkeyPatchDomSetAttributeToAllowAtSymbols()

// We're defining these globals and methods inside this function (instead of outside)
// because it's an async function and if run twice, they would overwrite
// each other.
Expand Down Expand Up @@ -384,3 +386,32 @@ function initializeAlpineOnTo(from, to, childrenOnly) {
window.Alpine.clone(from, to)
}
}

let patched = false

function monkeyPatchDomSetAttributeToAllowAtSymbols() {
if (patched) return

patched = true

// Because morphdom may add attributes to elements containing "@" symbols
// like in the case of an Alpine `@click` directive, we have to patch
// the standard Element.setAttribute method to allow this to work.
let original = Element.prototype.setAttribute

let hostDiv = document.createElement('div')

Element.prototype.setAttribute = function newSetAttribute(name, value) {
if (! name.includes('@')) {
return original.call(this, name, value)
}

hostDiv.innerHTML = `<span ${name}="${value}"></span>`

let attr = hostDiv.firstElementChild.getAttributeNode(name)

hostDiv.firstElementChild.removeAttributeNode(attr)

this.setAttributeNode(attr)
}
}

0 comments on commit f9e4473

Please sign in to comment.