Skip to content

Commit 32653ec

Browse files
author
scrhartley
committed
Evaluate hx-vals with "this" referring to the element it is defined on
1 parent 5b4d77d commit 32653ec

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
@@ -3878,9 +3878,9 @@ var htmx = (function() {
38783878
if (evaluateValue) {
38793879
varsValues = maybeEval(elt, function() {
38803880
if (event) {
3881-
return Function('event', 'return (' + str + ')')(event)
3881+
return Function('event', 'return (' + str + ')').call(elt, event)
38823882
} else { // allow window.event to be accessible
3883-
return Function('return (' + str + ')')()
3883+
return Function('return (' + str + ')').call(elt)
38843884
}
38853885
}, {})
38863886
} 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)