Skip to content

Commit

Permalink
feature: js:myFunc
Browse files Browse the repository at this point in the history
Release 0.1.7
  • Loading branch information
ernestmarcinko committed Oct 18, 2023
1 parent 1bd7ef3 commit c2fb87b
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 18 deletions.
2 changes: 1 addition & 1 deletion dist/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 17 additions & 5 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,14 @@ <h1>Buttons</h1>
</form>
</p>

<span class="counter"></span>
<button hx-get="/example" hx-target="previous .counter" hx-trigger="load, click" hx-vals='js:{myVal: i++}' hx-ext="serverless">Click to Increment</button>

<p>
<button hx-get="/example" hx-target="next .counter" hx-trigger="load, click" hx-vals='js:{myVal: i++}' hx-ext="serverless">Click to Increment</button>
<span class="counter"></span>
</p>
<p>
<button hx-get="js:myFunc" hx-target="next .counter" hx-trigger="load, click" hx-vals='js:{myVal: j++}' hx-ext="serverless">Click to Increment</button>
<span class="counter"></span>
</p>

<script>
htmxServerless.handlers.set('/clicked', '<button hx-post="/clicked2" hx-swap="outerHTML" hx-ext="serverless">Click again!</button>')
Expand All @@ -65,9 +70,16 @@ <h1>Buttons</h1>
// DIV
let i = 0;
htmxServerless.handlers.set('/example', function(text, params, xhr){
let status = params?.myVal < 10 ? "smaller" : "bigger";
return `Value of "i" is: ${i}, it is ${status} than 10. Click to increment!`;
let status = params?.myVal < 10 ? "smaller or equals to" : "bigger than";
return `Value of "myVal" is: ${params?.myVal}, it is ${status} 10.`;
});

// Custom hander with js:myFunc()
let j = 0;
function myFunc(text, params, xhr){
let status = params?.myVal < 10 ? "smaller or equals to" : "bigger than";
return `Value of "myVal" is: ${params?.myVal}, it is ${status} 10.`;
}
</script>
</body>
</html>
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "htmx-serverless",
"version": "0.1.6",
"description": "HTMX serverless XHR requests",
"version": "0.1.7",
"description": "HTMX Serverless XHR requests. A frontend tool to define custom client states without mock XHR server.",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
Expand Down
48 changes: 39 additions & 9 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ htmxServerless.handlers.set('/handler2', function(text, params, xhr){
console.log(this, text, params, xhr);
return "<p>Okay!</p>";
});

// Directly within the hx-{request} attribute, return value of myFunc is the replacement
<button hx-get="js:myFunc" hx-swap="outerHTML" hx-ext="serverless">
Click to replace via myFunc!
</button>
```

### In custom bundles
Expand Down Expand Up @@ -64,37 +69,63 @@ The button is then replaced with the HTML defined without triggering a request t

[Try this example here.](https://jsfiddle.net/ernestmarcinko/h0rj5pez/1/)

### Handler as a Function
### Handler as a Function set excplicitly

Tha handler function is a great tool for more complex conditional logic, like it would happen on the server side.
Let's make a simple click based number increment handler:

```html
<span class="counter"></span>
<button hx-get="/example"
hx-target="previous .counter"
<button hx-get="/count"
hx-target="next .counter"
hx-trigger="load, click"
hx-vals='js:{myVal: i++}'
hx-ext="serverless">Click to Increment</button>
<span class="counter"></span>

```

The handler only needs to print the text as "i" is incremented by hx-vals automatically:

```javascript
let i = 0;
htmxServerless.handlers.set('/example', function(text, params, xhr){
let status = params?.myVal < 10 ? "smaller" : "bigger";
return `Value of "i" is: ${i}, it is ${status} than 10`;
htmxServerless.handlers.set('/count', function(text, params, xhr){
let status = params?.myVal < 10 ? "smaller or equals to" : "bigger than";
return `Value of "myVal" is: ${params?.myVal}, it is ${status} 10.`;
});
```
[Try this example here.](https://jsfiddle.net/ernestmarcinko/vzpawq0y/1/)
[Try this example here.](https://jsfiddle.net/ernestmarcinko/fm4tu9q8/2/)
Output:
![Alt text](img/auto-increment.png)
### Handler as a Function via js:myFunc
You can set the handler function implicitly in the hx-{get,post etc..} attribute via the js:myFunc syntax:
```html
<button hx-get="js:counter"
hx-target="next .counter"
hx-trigger="load, click"
hx-vals='js:{myVal: i++}'
hx-ext="serverless">Click to Increment</button>
<span class="counter"></span>
```
The handler function accepts the same arguments as before:
```javascript
let i = 0;
function counter(text, params, xhr){
let status = params?.myVal < 10 ? "smaller or equals to" : "bigger than";
return `Value of "myVal" is: ${params?.myVal}, it is ${status} 10.`;
}
```
[Try this example here.](https://jsfiddle.net/ernestmarcinko/x3kdownf/3/)
## Handler function
The handler function accepts 3 parameters (4 including "this") and returns a string:
Expand All @@ -118,7 +149,6 @@ function handler(text, params, xhr){
console.log(this, text, params, xhr);
return 'Hi!';
}
htmxServerless.handlers.set('/example', handler);
```
## How does it work?
Expand Down
1 change: 1 addition & 0 deletions src/Serverless.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ export default class Serverless {
init(h?: typeof htmx): void;
onEvent(name: string, evt: any): void;
transformResponse(text: string, xhr: XHRServerless, elt: HtmxElement): string;
parseHandlers(path: string | undefined): void;
shouldIntercept(path: string | undefined): boolean;
}
13 changes: 12 additions & 1 deletion src/Serverless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default class Serverless {
onEvent(name: string, evt: any) {
const path:path = evt?.detail?.elt?.['htmx-internal-data']?.path;
const params:params = evt.detail?.requestConfig?.parameters;
name === "htmx:beforeSend" && this.parseHandlers(path);

if (
typeof evt.detail.xhr !== 'undefined' &&
Expand Down Expand Up @@ -56,7 +57,17 @@ export default class Serverless {
return text;
}

parseHandlers(path:string|undefined) {
path = path ?? '';
if ( !this.handlers.has(path) && path.startsWith('js:') ) {
const handler = path.replace(/js:|\(\)/g, '').trim();
if ( handler !== '' ) {
this.handlers.set(path, Function("return ("+ handler +")")());
}
}
}

shouldIntercept(path:string|undefined) {
return this.handlers.has( path ?? '');
return this.handlers.has(path ?? '');
}
}

0 comments on commit c2fb87b

Please sign in to comment.