Stimulus Discourse

Onsenui events in stimulusjs


#1

Hi,

How to get onsenui events in stimulusjs ?

I am converting below example to stimulujs.

https://onsen.io/playground/?framework=vanilla&category=reference&module=page

Thanks.


#2

You can install events on the document by appending @document to the event name in the action descriptor.

Code: https://glitch.com/edit/#!/stimulus-onsen-ui-events
App: https://stimulus-onsen-ui-events.glitch.me

<ons-page data-controller="onsen--lifecycle" data-action="init@document->onsen--lifecycle#init">
  <!-- ... --> 
</ons-page>
// onsen/lifecycle_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
  init(event) {
    console.log('This is a lifecycle event!', event.target);

    var page = event.target;
    if (page.matches('#helloworld-page')) {
      page.querySelector('ons-toolbar .center').innerHTML = 'My app';
      page.querySelector('ons-button').onclick = function() {
        window.ons.notification.alert('Hello world!');
      };
    }
  }
}

#3

thanks @kaspermeyer

I pushed the code in to initialize function as below and it works fine.

import { Controller } from 'stimulus'

import ons from 'onsenui'

export default class extends Controller {

  initialize() {

  document.addEventListener('init', function(event) {
  console.log('This is a lifecycle event!', event.target);

  var page = event.target;
  if (page.matches('#helloworld-page')) {
    page.querySelector('ons-toolbar .center').innerHTML = 'My app';
    page.querySelector('ons-button').onclick = function() {
      ons.notification.alert('Hello world!');
    };
  }
});
  }