or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdcore-framework.mddatabase-models.mdevent-system.mdindex.mdstyling-theming.mdui-components.md

event-system.mddocs/

0

# Event System

1

2

Type-safe event handling system connecting frontend interactions to backend state changes with automatic synchronization, JavaScript integration, and comprehensive DOM manipulation capabilities.

3

4

## Capabilities

5

6

### Event Handler Creation

7

8

Core event handling mechanisms for connecting UI interactions to state changes with type safety and automatic serialization.

9

10

```python { .api }

11

def event(fn: Callable) -> EventHandler:

12

"""

13

Create an event handler from a function.

14

15

Converts a regular function into a Reflex event handler that can

16

be triggered from frontend interactions and automatically updates state.

17

18

Args:

19

fn: Function to convert to event handler

20

21

Returns:

22

EventHandler instance with automatic state synchronization

23

"""

24

...

25

26

class EventHandler:

27

"""

28

Core event handler implementation for state changes.

29

30

Represents a callable event that can be triggered from the frontend

31

and executes backend logic with automatic state synchronization.

32

"""

33

34

fn: Callable

35

"""The underlying function to execute."""

36

37

args: tuple

38

"""Arguments to pass to the function."""

39

40

kwargs: dict

41

"""Keyword arguments to pass to the function."""

42

43

def __init__(self, fn: Callable, args: tuple = (), kwargs: dict = None) -> None:

44

"""

45

Initialize event handler with function and arguments.

46

47

Args:

48

fn: Function to wrap as event handler

49

args: Positional arguments for the function

50

kwargs: Keyword arguments for the function

51

"""

52

...

53

54

def __call__(self, *args, **kwargs) -> EventHandler:

55

"""

56

Create new event handler with additional arguments.

57

58

Args:

59

*args: Additional positional arguments

60

**kwargs: Additional keyword arguments

61

62

Returns:

63

New EventHandler with combined arguments

64

"""

65

...

66

67

class EventChain:

68

"""

69

Chain multiple event handlers to execute in sequence.

70

71

Allows combining multiple event handlers that execute one after

72

another, useful for complex interactions requiring multiple actions.

73

"""

74

75

events: list[EventHandler]

76

"""List of event handlers to execute in sequence."""

77

78

def __init__(self, *events: EventHandler) -> None:

79

"""

80

Initialize event chain with handlers.

81

82

Args:

83

*events: Event handlers to execute in order

84

"""

85

...

86

87

def add_event(self, event: EventHandler) -> EventChain:

88

"""

89

Add another event handler to the chain.

90

91

Args:

92

event: Event handler to append to chain

93

94

Returns:

95

Updated event chain with new handler

96

"""

97

...

98

```

99

100

### Browser Actions

101

102

Direct browser manipulation and interaction capabilities for enhanced user experience and integration with browser APIs.

103

104

```python { .api }

105

def redirect(

106

path: str | Var[str],

107

is_external: bool = False,

108

replace: bool = False,

109

) -> EventSpec:

110

"""

111

Redirect to a new path.

112

113

Args:

114

path: The path to redirect to

115

is_external: Whether to open in new tab or not

116

replace: If True, the current page will not create a new history entry

117

118

Returns:

119

EventSpec that performs navigation when triggered

120

"""

121

...

122

123

def console_log(message: str | Var[str]) -> EventSpec:

124

"""

125

Do a console.log on the browser.

126

127

Args:

128

message: The message to log

129

130

Returns:

131

An event to log the message

132

"""

133

...

134

135

def window_alert(message: str | Var[str]) -> EventSpec:

136

"""

137

Create a window alert on the browser.

138

139

Args:

140

message: The message to alert

141

142

Returns:

143

An event to alert the message

144

"""

145

...

146

147

def download(

148

url: str | Var | None = None,

149

filename: str | Var | None = None,

150

data: str | bytes | Var | None = None,

151

) -> EventSpec:

152

"""

153

Download the file at a given path or with the specified data.

154

155

Args:

156

url: The URL to the file to download

157

filename: The name that the file should be saved as after download

158

data: The data to download

159

160

Returns:

161

EventSpec that triggers download when executed

162

"""

163

...

164

165

def set_clipboard(content: str | Var[str]) -> EventSpec:

166

"""

167

Set the text in content in the clipboard.

168

169

Args:

170

content: The text to add to clipboard

171

172

Returns:

173

EventSpec: An event to set some content in the clipboard

174

"""

175

...

176

177

def set_focus(element_id: str) -> EventHandler:

178

"""

179

Set focus to a specific element by ID.

180

181

Args:

182

element_id: DOM element ID to focus

183

184

Returns:

185

EventHandler that focuses element when triggered

186

"""

187

...

188

189

def scroll_to(elem_id: str, align_to_top: bool | Var[bool] = True) -> EventSpec:

190

"""

191

Select the id of a html element for scrolling into view.

192

193

Args:

194

elem_id: The id of the element to scroll to

195

align_to_top: Whether to scroll to the top (True) or bottom (False) of the element

196

197

Returns:

198

An EventSpec to scroll the page to the selected element

199

"""

200

...

201

202

def set_value(element_id: str, value: str) -> EventHandler:

203

"""

204

Set the value of a form element.

205

206

Args:

207

element_id: Form element ID to update

208

value: New value to set

209

210

Returns:

211

EventHandler that updates element value when triggered

212

"""

213

...

214

```

215

216

### Storage Management

217

218

Browser storage manipulation for client-side data persistence using localStorage, sessionStorage, and cookies.

219

220

```python { .api }

221

def clear_local_storage() -> EventHandler:

222

"""

223

Clear all browser localStorage data.

224

225

Removes all key-value pairs from browser localStorage,

226

useful for logout functionality or data cleanup.

227

228

Returns:

229

EventHandler that clears localStorage when triggered

230

"""

231

...

232

233

def remove_local_storage(key: str) -> EventHandler:

234

"""

235

Remove specific key from localStorage.

236

237

Args:

238

key: localStorage key to remove

239

240

Returns:

241

EventHandler that removes localStorage item when triggered

242

"""

243

...

244

245

def clear_session_storage() -> EventHandler:

246

"""

247

Clear all browser sessionStorage data.

248

249

Returns:

250

EventHandler that clears sessionStorage when triggered

251

"""

252

...

253

254

def remove_session_storage(key: str) -> EventHandler:

255

"""

256

Remove specific key from sessionStorage.

257

258

Args:

259

key: sessionStorage key to remove

260

261

Returns:

262

EventHandler that removes sessionStorage item when triggered

263

"""

264

...

265

266

def remove_cookie(name: str, path: str = "/") -> EventHandler:

267

"""

268

Remove browser cookie by name.

269

270

Args:

271

name: Cookie name to remove

272

path: Cookie path (defaults to root path)

273

274

Returns:

275

EventHandler that removes cookie when triggered

276

"""

277

...

278

```

279

280

### JavaScript Integration

281

282

Direct JavaScript code execution and function calls for advanced browser interactions and third-party library integration.

283

284

```python { .api }

285

def call_script(script: str) -> EventHandler:

286

"""

287

Execute arbitrary JavaScript code in the browser.

288

289

Allows running custom JavaScript code for advanced interactions,

290

third-party library integration, or browser API access.

291

292

Args:

293

script: JavaScript code string to execute

294

295

Returns:

296

EventHandler that executes JavaScript when triggered

297

"""

298

...

299

300

def run_script(script: str) -> EventHandler:

301

"""

302

Alias for call_script - execute JavaScript code.

303

304

Args:

305

script: JavaScript code string to execute

306

307

Returns:

308

EventHandler that runs JavaScript when triggered

309

"""

310

...

311

312

def call_function(function_name: str, *args) -> EventHandler:

313

"""

314

Call a specific JavaScript function with arguments.

315

316

Invokes a JavaScript function available in the global scope

317

with the provided arguments, useful for library integration.

318

319

Args:

320

function_name: Name of JavaScript function to call

321

*args: Arguments to pass to the JavaScript function

322

323

Returns:

324

EventHandler that calls JavaScript function when triggered

325

"""

326

...

327

```

328

329

### Event Control

330

331

Event flow control mechanisms for managing event propagation, preventing default behaviors, and handling edge cases.

332

333

```python { .api }

334

def prevent_default() -> EventHandler:

335

"""

336

Prevent default browser behavior for an event.

337

338

Calls preventDefault() on the DOM event to stop default

339

browser actions like form submission or link navigation.

340

341

Returns:

342

EventHandler that prevents default behavior when triggered

343

"""

344

...

345

346

def stop_propagation() -> EventHandler:

347

"""

348

Stop event from bubbling up the DOM tree.

349

350

Calls stopPropagation() on the DOM event to prevent it

351

from triggering handlers on parent elements.

352

353

Returns:

354

EventHandler that stops event propagation when triggered

355

"""

356

...

357

358

def noop() -> EventHandler:

359

"""

360

No-operation event handler that does nothing.

361

362

Useful as a placeholder or to disable event handling

363

temporarily while maintaining component interfaces.

364

365

Returns:

366

EventHandler that performs no action when triggered

367

"""

368

...

369

```

370

371

### File Upload Events

372

373

Specialized event handlers for file upload operations with progress tracking and validation support.

374

375

```python { .api }

376

def upload_files(

377

upload_id: str = "",

378

multiple: bool = False

379

) -> EventHandler:

380

"""

381

Trigger file upload dialog and handle file selection.

382

383

Opens browser file picker and processes selected files

384

through the Reflex upload system with progress tracking.

385

386

Args:

387

upload_id: Unique identifier for upload session

388

multiple: Whether to allow multiple file selection

389

390

Returns:

391

EventHandler that manages file upload process when triggered

392

"""

393

...

394

```

395

396

### Client-Side Storage Components

397

398

Reactive storage classes for integrating browser storage with Reflex state management for persistent application data.

399

400

```python { .api }

401

class Cookie:

402

"""

403

Browser cookie state storage integration.

404

405

Provides reactive interface to browser cookies with automatic

406

state synchronization and expiration management.

407

"""

408

409

name: str

410

"""Cookie name identifier."""

411

412

value: Any

413

"""Current cookie value (automatically serialized)."""

414

415

max_age: int | None = None

416

"""Cookie expiration in seconds (None for session cookie)."""

417

418

path: str = "/"

419

"""Cookie path scope."""

420

421

domain: str | None = None

422

"""Cookie domain scope."""

423

424

secure: bool = False

425

"""Whether cookie requires HTTPS."""

426

427

same_site: str = "lax"

428

"""SameSite cookie policy ('strict', 'lax', 'none')."""

429

430

def __init__(self, name: str, **kwargs) -> None:

431

"""

432

Initialize cookie storage with configuration.

433

434

Args:

435

name: Cookie name

436

**kwargs: Cookie configuration options

437

"""

438

...

439

440

class LocalStorage:

441

"""

442

Browser localStorage integration for persistent state.

443

444

Provides reactive interface to browser localStorage with

445

automatic JSON serialization and state synchronization.

446

"""

447

448

key: str

449

"""localStorage key identifier."""

450

451

value: Any

452

"""Current stored value (automatically serialized to JSON)."""

453

454

def __init__(self, key: str, default: Any = None) -> None:

455

"""

456

Initialize localStorage integration.

457

458

Args:

459

key: localStorage key name

460

default: Default value if key doesn't exist

461

"""

462

...

463

464

class SessionStorage:

465

"""

466

Browser sessionStorage integration for temporary state.

467

468

Similar to LocalStorage but data expires when browser tab closes.

469

Useful for temporary application state and user sessions.

470

"""

471

472

key: str

473

"""sessionStorage key identifier."""

474

475

value: Any

476

"""Current stored value (automatically serialized to JSON)."""

477

478

def __init__(self, key: str, default: Any = None) -> None:

479

"""

480

Initialize sessionStorage integration.

481

482

Args:

483

key: sessionStorage key name

484

default: Default value if key doesn't exist

485

"""

486

...

487

```

488

489

### State Retrieval Utilities

490

491

Utility functions for accessing and manipulating state from within event handlers and computed variables.

492

493

```python { .api }

494

def get_state(state_class: type[State]) -> State:

495

"""

496

Retrieve current state instance within event handlers.

497

498

Provides access to state instance for reading values or calling

499

methods from within event handlers or computed variables.

500

501

Args:

502

state_class: State class to retrieve instance for

503

504

Returns:

505

Current state instance of the specified class

506

"""

507

...

508

```

509

510

## Usage Examples

511

512

### Basic Event Handling

513

514

```python

515

import reflex as rx

516

517

class CounterState(rx.State):

518

count: int = 0

519

520

def increment(self):

521

self.count += 1

522

523

def decrement(self):

524

self.count -= 1

525

526

def reset(self):

527

self.count = 0

528

529

def counter():

530

return rx.vstack(

531

rx.heading(f"Count: {CounterState.count}"),

532

rx.hstack(

533

rx.button("Decrement", on_click=CounterState.decrement),

534

rx.button("Reset", on_click=CounterState.reset),

535

rx.button("Increment", on_click=CounterState.increment),

536

),

537

)

538

```

539

540

### Event Chaining

541

542

```python

543

class FormState(rx.State):

544

submitted: bool = False

545

546

def submit_form(self):

547

self.submitted = True

548

# Process form data

549

550

def show_success(self):

551

return rx.toast.success("Form submitted successfully!")

552

553

def form():

554

return rx.form(

555

# ... form fields ...

556

rx.button(

557

"Submit",

558

on_click=[

559

FormState.submit_form,

560

FormState.show_success,

561

rx.redirect("/success")

562

]

563

)

564

)

565

```

566

567

### Storage Integration

568

569

```python

570

class UserState(rx.State):

571

# Persistent user preferences in localStorage

572

theme: str = rx.LocalStorage("user_theme", "light")

573

574

# Session data that expires with tab

575

session_data: dict = rx.SessionStorage("session", {})

576

577

# Authentication cookie

578

auth_token: str = rx.Cookie("auth", max_age=86400) # 24 hours

579

```

580

581

## Types

582

583

```python { .api }

584

from typing import Any, Callable, Dict, List, Optional, Union

585

from reflex.vars.base import Var

586

587

# Event Types

588

EventType = Callable | EventHandler | list[EventHandler]

589

EventFunc = Callable[..., Any] # Function that can become event handler

590

591

# Event Handler Types

592

class Event:

593

"""DOM event data from frontend."""

594

token: str

595

name: str

596

router_data: Dict[str, Any]

597

payload: Dict[str, Any]

598

599

# Storage Types

600

CookieOptions = Dict[str, Union[str, int, bool]]

601

StorageValue = Union[str, int, float, bool, Dict, List]

602

603

# JavaScript Integration Types

604

JavaScriptCode = str # JavaScript code string

605

FunctionName = str # JavaScript function name

606

FunctionArgs = List[Any] # Arguments for JavaScript functions

607

608

# Browser Action Types

609

URLPath = str # URL or route path

610

ElementID = str # DOM element ID

611

LogLevel = Literal["info", "warn", "error", "debug"]

612

ScrollBehavior = Literal["smooth", "instant", "auto"]

613

```