mirror of
https://github.com/bigskysoftware/htmx.git
synced 2026-03-03 20:48:34 +00:00
introduce htmx scripting API concept
This commit is contained in:
parent
871a5c6147
commit
9515515bfe
26
src/htmx.js
26
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)
|
||||
|
||||
@ -38,4 +38,17 @@ describe('hx-on attribute', function() {
|
||||
delete window.foo
|
||||
})
|
||||
|
||||
it('htmx API works', async function () {
|
||||
var btn = initHTML(
|
||||
`<button hx-on:foo='await timeout(1); window.foo = 10'>
|
||||
Foo
|
||||
</button>`)
|
||||
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
|
||||
})
|
||||
|
||||
})
|
||||
Loading…
x
Reference in New Issue
Block a user