diff --git a/src/htmx.js b/src/htmx.js index 85ff26b4..8ecb429f 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -51,6 +51,7 @@ var htmx = (() => { class Htmx { + #scriptingAPIMethods = ['timeout']; __mutationObserver = new MutationObserver((records) => this.__onMutation(records)); __actionSelector = "[hx-action],[hx-get],[hx-post],[hx-put],[hx-patch],[hx-delete]"; __boostSelector = "a,form"; @@ -103,7 +104,8 @@ var htmx = (() => { initialDelay: 500, maxDelay: 30000, pauseHidden: false - } + }, + scriptingAPI : this.__initScriptingAPI() } let metaConfig = this.find('meta[name="htmx:config"]'); if (metaConfig) { @@ -133,6 +135,14 @@ var htmx = (() => { return value } + __initScriptingAPI() { + let api = {} + for (let methodName of this.#scriptingAPIMethods) { + api[methodName] = this[methodName].bind(this) + } + return api + } + __tokenize(str) { let tokens = [], i = 0; while (i < str.length) { @@ -875,16 +885,22 @@ var htmx = (() => { } async __executeJavaScriptAsync(thisArg, obj, code, expression = true) { - let keys = Object.keys(obj); - let values = Object.values(obj); + let args = {} + Object.assign(args, this.config.scriptingAPI) + Object.assign(args, obj) + let keys = Object.keys(args); + let values = Object.values(args); let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor; let func = new AsyncFunction(...keys, expression ? `return (${code})` : code); return await func.call(thisArg, ...values); } __executeJavaScript(thisArg, obj, code, expression = true) { - let keys = Object.keys(obj); - let values = Object.values(obj); + let args = {} + Object.assign(args, this.config.scriptingAPI) + Object.assign(args, obj) + let keys = Object.keys(args); + let values = Object.values(args); let func = new Function(...keys, expression ? `return (${code})` : code); let tmp = func.call(thisArg, ...values); console.log("1", tmp) diff --git a/test/tests/attributes/hx-on.js b/test/tests/attributes/hx-on.js index c522f4ed..77c379fa 100644 --- a/test/tests/attributes/hx-on.js +++ b/test/tests/attributes/hx-on.js @@ -38,4 +38,17 @@ describe('hx-on attribute', function() { delete window.foo }) + it('htmx API works', async function () { + var btn = initHTML( + ``) + let evt = new CustomEvent("foo"); + btn.dispatchEvent(evt) + assert.equal(window.foo, undefined); + await htmx.timeout(10); + assert.equal(window.foo, 10); + delete window.foo + }) + }) \ No newline at end of file