rishavs / vanillajs-spa

a simple SPA in vanilla js
343 stars 107 forks source link

HTML template event binding #2

Closed mm-ns closed 5 years ago

mm-ns commented 5 years ago

Hi There

First thanks for this great project :)

I wanted to know how can i bind an event, say onChange on a select, to a function that's in an external controller.

I import the controller like so:

import HomeController from '../../js/controllers/HomeController.js';

and my select (part of the template) looks like this

<select class="custom-select" onChange="displayMarkers(this.value)">

I cannot seem to make this work in any way. Any example would be appreciated...

rishavs commented 5 years ago

essentially the problem is that you are trying to fire the onchange event and call the event before the function is declared.

So, in my code i am not using any script tags or calling functions in the html tags.

Instead, all my controls and event based function calls (button clicks, submits etc.) I am calling in the after_render() function.

So whenever I have to render a page, I first call the render function which adds all the dom elements. Then I call the after_render function which registers all my html events.

this file shows the concept in action.

https://github.com/rishavs/vanillajs-spa/blob/master/src/views/pages/Register.js

mm-ns commented 5 years ago

Hi Rishavs.

Sounds great, it's exactly what I ended up doing too :)

thanks a lot.

rishavs commented 5 years ago

Glad to be of help. :)