#listen() handler not being called at first?

10 messages · Page 1 of 1 (latest)

harsh pewter
#

The JS below calls listen() then init_page(), which calls the initialize_view() command, which emit()s an update_vm event, but the listen()ing handler does not get called. This first event is meant to hydrate the page. Apparently the event is not delivered.

Clicking a button causes a (different) command to be called, which then emit()s the same update_vm event, which is delivered.

This surprises me... what am I missing?

Thanks!!!

JS:

listen('update_view', handle__update_view__event);
console.log("listen()ed");

//...

function init_page() {
  invoke('initialize_view');
  document.body.style.display = "block";
}

if (document.readyState != "loading") {
  init_page();
} else {
  window.addEventListener("DOMContentLoaded", init_page);
}

main.rs:

fn update_view(window: &Window, vm: &ViewModel) {
    eprintln!("update_view(vm: {vm:?})");
    window.emit("update_view", &vm).expect("emit(update_view) failed");
}

fn mut_vm<F>(window: &Window, vm: &Arc<Mutex<ViewModel>>, f: F)
    where F: FnOnce(&mut ViewModel)
{
    let mut guarded_vm = vm.lock().expect("vm.lock() failed");
    f(guarded_vm.deref_mut());
    update_view(&window, &*guarded_vm);
}

#[tauri::command]
fn initialize_view(window: Window, vm: State<Arc<Mutex<ViewModel>>>) {
    println!("initialize_view()");
    mut_vm(&window, &vm, |vm| vm.app_state = AppState::MainPage); // TODO: remove, just emit the event
}

Console output:

 
tauri://localhost/main.js:44:12: CONSOLE LOG listen()ed
initialize_view()
update_view(vm: ViewModel { app_state: MainPage, pedal_connected: false, drive_connected: false })
    <==== should see '... CONSOLE LOG handle__update_view__event'

After clicking a button:

update_view(vm: ViewModel { app_state: StartPage, pedal_connected: false, drive_connected: false })
tauri://localhost/view_interface.js:156:14: CONSOLE LOG handle__update_view__event
... more logging as the page is hydrated ...
#

listen() handler not being called at first?

native cosmos
#

Since it looks like you're targeting a specific window for events, have you tried appWindow.listen or getCurrent().listen instead of global listens? I know this confused me as well.

lament eagle
#

Another thing to try is to await listen() since it is a Promise.

#

Of course the handler should still run regardless, but sometimes there is a cleanup (explicit or implicit) that happens before it receives an event.

harsh pewter
harsh pewter
lament eagle
harsh pewter
#

Plus, I'm a newbie to this, so I didn't notice the async nature.