Search code examples
eventsdartbootstrap-modaldart-htmldart2js

Handling bootstrap4 modals in Dart


I need to call bootstrap modals from Dart code and this is what I've tried (using the js library):

@JS('jQuery')
class jQuery {

  @JS()
  jQuery(obj);

  @JS('modal')
  external dynamic modal(func);
}

class Modal extends jQuery {

  Modal(obj) : super(obj);

  dynamic toggle() => super.modal('toggle');
  dynamic show() => super.modal('show');
  dynamic hide() => super.modal('hide');
  dynamic handleUpdate() => super.modal('handleUpdate');
  dynamic dispose() => super.modal('dispose');

}

in that code if I use the jQuery class directly I get no issues (jQuery.modal('show')) but if I use the Modal methods i.e.:

Modal modal = Modal('#myModal');
modal.toggle();

I will get a TypeError: Cannot read property 'call' of undefined (NullError) .

The javascript the code is jQuery('#myModal').modal(func)

My second issue is how to hook a custom event for example: show.bs.modal in jQuery I would use .on(...) but in Dart I have no clue, I've used element.addEventListener('show.bs.modal', onModalShown) but it isn't triggered and I don't get any errors.


Solution

  • you defined the jquery class but you need to get it from the window and you also need to defined you modal using @JS annotation, I don't think you can extend the jQuery class

    I would have done like that

    @JS('\$')
    external dynamic jQuery(query);
    
    @JS()
    @anonymous
    class ModalElement {
      external modal(String call);
      external on(String event, Function callback);
      ...
    }
    
    final modal = jQuery('#myModal') as ModalElement;
    modal.modal('toggle');
    
    modal.on('event', allowInterop((event) {}));