Skip to content

Commit

Permalink
docs(custom_js): expend example with JSEval
Browse files Browse the repository at this point in the history
  • Loading branch information
jourdain committed Jan 17, 2024
1 parent 38de8e6 commit f59d512
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
5 changes: 5 additions & 0 deletions examples/09_advanced/custom_js/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
This example load a JS file on disk to make it available for the trame template.

For that we extend the existing `window.trame.utils` container with our helper functions to be used in our template expression as `utils.my_code.*`.

On top of that we illustrate some usage of JSEval component for executing custom JS.
24 changes: 23 additions & 1 deletion examples/09_advanced/custom_js/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from pathlib import Path

from trame.app import get_server
from trame.widgets import vuetify3
from trame.widgets import vuetify3, client
from trame.ui.vuetify3 import SinglePageLayout


Expand All @@ -26,8 +26,30 @@ def __init__(self, server=None, table_size=10):
# Make sure my js code get loaded on the client side
load_my_js(self.server)

@property
def state(self):
return self.server.state

@property
def ctrl(self):
return self.server.controller

def trigger_alert(self):
self.ctrl.js_eval(f"server({self.state.name})")

def _build_ui(self):
with SinglePageLayout(self.server, full_height=True) as layout:
self.ctrl.js_eval = client.JSEval(
exec="utils.my_code.actions.hello($event)"
).exec
with layout.toolbar:
vuetify3.VTextField(
v_model=("name", "world"),
density="compact",
hide_details=True,
)
vuetify3.VBtn("Local JS", click="utils.my_code.actions.hello(name)")
vuetify3.VBtn("JS from Py", click=self.trigger_alert)
with layout.content:
vuetify3.VTextField(
v_model=("text_1", "1.2"),
Expand Down
5 changes: 5 additions & 0 deletions examples/09_advanced/custom_js/my_utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// global trame.utils can be extended by users
// - within template definition, it can be accessed as "utils.my_code.rules.int"
window.trame.utils.my_code = {
actions: {
hello(name) {
alert(`This alert was triggered by my_code for ${name}`)
},
},
rules: {
number(v) {
if (Number.isNaN(Number(v))) {
Expand Down

0 comments on commit f59d512

Please sign in to comment.