Skip to content

Commit e2353e2

Browse files
scrhartleyscrhartley
andauthored
Allow use of "this" when evaluating hx-vals (#3332)
Evaluate hx-vals with "this" referring to the element it is defined on Co-authored-by: scrhartley <scrhartley@github.com>
1 parent dc71b31 commit e2353e2

3 files changed

Lines changed: 15 additions & 2 deletions

File tree

src/htmx.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3914,9 +3914,9 @@ var htmx = (function() {
39143914
if (evaluateValue) {
39153915
varsValues = maybeEval(elt, function() {
39163916
if (event) {
3917-
return Function('event', 'return (' + str + ')')(event)
3917+
return Function('event', 'return (' + str + ')').call(elt, event)
39183918
} else { // allow window.event to be accessible
3919-
return Function('return (' + str + ')')()
3919+
return Function('return (' + str + ')').call(elt)
39203920
}
39213921
}, {})
39223922
} else {

test/attributes/hx-vals.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,4 +364,16 @@ describe('hx-vals attribute', function() {
364364
this.server.respond()
365365
div.innerHTML.should.equal('Clicked!')
366366
})
367+
368+
it('js: this refers to the element with the hx-vals attribute', function() {
369+
this.server.respondWith('POST', '/vars', function(xhr) {
370+
var params = getParameters(xhr)
371+
params.i1.should.equal('test')
372+
xhr.respond(200, {}, 'Clicked!')
373+
})
374+
var div = make('<div hx-post="/vars" hx-vals="javascript:{ ...this.dataset }" data-i1="test"></div>')
375+
div.click()
376+
this.server.respond()
377+
div.innerHTML.should.equal('Clicked!')
378+
})
367379
})

www/content/attributes/hx-vals.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,4 @@ In this example, if `foo()` returns an object like `{name: "John", age: 30}`, bo
4545
* `hx-vals` is inherited and can be placed on a parent element.
4646
* A child declaration of a variable overrides a parent declaration.
4747
* Input values with the same name will be overridden by variable declarations.
48+
* When using `javascript:`, `this` refers to the element with the `hx-vals` attribute

0 commit comments

Comments
 (0)