Have Stimulus wait for Dom changes using MutationObserver custom event listener before continuing - ruby-on-rails

I am writing a Stimulus controller that has a function which needs wot wait for DOM changes before it can continue (As a Turbo Stream response needs to update a frame). Before the DOM change, it can't find the target, but it should be able to AFTER the DOM change.
I have successfully enabled MutationObserver, which is able to tell me that the child element was added--but this happens after the function/action is looking for it.
Therefore I found this article on how to use Mutation Observer to add a custom Event Listener.
I've gotten it to work as far as until the last step, where we code the Promise.
When I run the code, I get
undefined is not an object (evaluating "el.innerText.includes(text)
I tried changing it to
document.getElementByTagName(el).innerText.includes(text)
But that returned that it's not a function.
The instantiation of the MutationObserver is inside my connect() method:
connect() {
const observer = new MutationObserver( list => {
const evt = new CustomEvent('dom-changed', {detail: list});
document.body.dispatchEvent(evt)
});
observer.observe(document.body, {attributes: true, childList: true, subtree: true});
}
the waitforText(el, text, maxWait=5000) function is a controller action currently.
I then run this.waitForText("h1", "Settings for") inside the function I need it to wait. I'm merely using a h1 for testing before I put it on an element that is within the same frame as that h1.

Related

How do you return a Future based off a Stream you don't control in Dart?

I have a situation where I'm expecting a single value from a Stream, but because it's one provided by the browser I can't rely on simply calling streamSub.single. Currently, I'm creating an explicit StreamController so that I can easily generate a Future from it while guaranteeing that it will only get a single response. However, that ends up being a lot more overhead than I was expecting to have to set up, making me think I'm missing something. The current code follows:
StreamController<String> streamCtrlr = new StreamController<String>();
var popup = window.open(targetUrl, "Auth Window");
//The popup above will call window.opener.postMessage, so listen for messages
StreamSubscription sub = window.onMessage.listen(null);
sub.onData((Event){
/* Logic goes here */
sub.cancel();
popup.close();
streamCtrlr.add(Event.data);
streamCtrlr.close();
});
return streamCtrlr.stream.single;
How can this be re-written so that the intermediary StreamController isn't required?
Why can't you rely on calling streamSub.single? Is it because there might be more than one message?
Your example code picks the first event in all cases, so to get the same behavior, you can use window.onMessage.first instead of window.onMessage.single.
It will still cause an error if there is no first event (but I don't think that can happen with DOM event handlers - they never send a done event), and otherwise it will give a future that is completed with the first event.
You also want to extract the event data, so you will probably want:
return window.onMessage.first.then((event) {
/* Logic goes here */
popup.close();
return event.data;
});

jQuery UI dialog binding keydown doesn't always work

I'm writing my own ESC handler because I need to do other actions when ESC is pressed, specifically I need to manage where focus goes for keyboard-only users. I have it working for all menus and some dialogs (both of which are using jQueryUI) but I'm having problems with dialogs that open on top of other dialogs (confirmation dialogs).
I'm using a Backbone View and adding my keydown handler on dialogcreate. this.$el.on('dialogcreate', this.bindKeydownEvent);
My handler:
bindKeydownEvent: function(ev, ui) {
var self = this;
this.$el.dialog().on('keydown', function(evt) {
if(evt.keyCode === $.ui.keyCode.ESCAPE) {
self.$el.dialog("close");
if(self.options.closeFocusEl) {
$(self.options.closeFocusEl).focus();
}
evt.stopPropagation();
}
});
}
I've checked and this.$el.dialog() is the correct dialog when the second dialog calls this.bindKeydownEvent but for some reason the keydown handler is not being triggered no matter what I press in the dialog (Tab, Space, Enter, random letters, etc).
Any idea what I'm doing wrong or have a better way I could bind the keydown event?
EDIT:
I just noticed that this is also happening in some first-level dialogs. It looks like the only difference is the way we get the template and therefore create the interior of the dialog. In our Alert and Confirmation dialog classes, we define the template as an attribute on the object like this: template: _.template("<div><%= o.content %></div>"). In other views (in which the keydown binding works) we build the child elements and add them to the DOM of the dialog, set the template in the initialize function
this.options.template = 'navigation/CreateNewDialog.template';
or set it when we call the dialog
var closeConv = new views.CloseConversationDialogView({
confirm: this.closeConversationConfirmed,
content: i18n.t("closeConversationInput"),
template: "conversation/CloseConversationDialog.template"
});
closeConv.render();
Is there a reason that creating the template inline as an attribute on the view would not bind keydown correctly?
To understand why your event handler isn't being triggered you need first understand how event delegation works.
The key to event delegation in that events bubble up the DOM. So when you bind your event using this.$el.dialog().on('keydown',..., what you basically doing is listening to any keydown event that is triggered on your $el or it's descendants. In this case being that your second dialog isn't a descendant of your $el it's events won't bubble up to it and therefore don't trigger your handler.
To work around this you can either bind directly to your second dialog, or instead bind to a exisitng higher level element like the document. For example
$(document).on('keydown', '.myDialog', function() {...
The only thing my original attempt was missing was "widget". The widget method, according to api.jqueryui.com,
Returns a jQuery object containing the generated wrapper.
I don't see any documentation on what exactly $('.selector').dialog() returns but apparently it is not the same as $('.selector').dialog("widget"). I also changed on('keydown'... to just use the jQuery keydown instead.
bindKeydownEvent: function(ev, ui) {
var self = this;
this.$el.dialog("widget").keydown(function(evt) {
if(evt.keyCode === $.ui.keyCode.ESCAPE) {
self.$el.dialog("close");
if(self.options.closeFocusEl) {
$(self.options.closeFocusEl).focus();
}
evt.stopPropagation();
}
});
}

Why do I lose draggable after drag?

I just migrated to backbone and have a strange behaviour.
I attach draggable to an element which is created by a script, thus not directly available in DOM.
EDIT:
The element that is created is .nav, $("#viewer") as container is already in the DOM.
In plain jQuery i used .on and mousemove event for this and it worked.
With backbone I use the same in the initialize method:
initialize: function(options) {
this.viewer = $("#viewer");
this.viewer.on("mousemove", '.nav', function() {
$(this).draggable();
});
This seems to work, but only one time.
After dragging the element one time, I can't drag it anymore.
Are there conflicts with the events? Am I missing something?
You have to refer to $('#viewer') after you've called render(). initialize is called before render, and so the DOM element doesn't exist.
Also, use this.$('#viewer'), and it will grab the element (after render) even if it hasn't been appended to your page's DOM.
myView = new ExampleView({ model: myModel });
$(body).append(myView.render().el);
myView.onRender();
// -------------
// Now on your view:
onRender: function() {
this.viewer = this.$('#viewer');
this.viewer.on("mousemove", '.nav', function() {
$(this).draggable();
});
},
UPDATE
You can also, to make such things simpler, customize Backbone to automatically call the onRender() function after rendering, by triggering an event or something.
Marionette.js (a Backbone.js extension) has this built in and I use it all the time.
The solution finally was pretty easy:
make sure you dont use outdated versions of backbone.js and underscore!!
After i updated the versions to latest I made it work with:
render: function() {
this.viewer.on("mouseover", '.nav', function() {
if (!$(this).data("init")) {
$(this).data("init", true);
$(this).draggable();
}
});
Probably still not very elegant but i couldnt made the suggested onRender method from dc2 work.

JQuery passing arguments for On Change for an item added to DOM via AJAX

I have multiple HTML fragments that are inserted into my DOM as the result of AJAX call-backs.
Each of these fragments will contain a text box whose class is "quantity".
What I want to do is to create an "on change" event handler that fires whenever one of these textbox's text value is changed. However, when that event is fired/handled, I need to know WHICH specific textbox was updated.
Okay, using jQuery, I have the following that fires in my "Lists.initHandlers" method:
$(document).on('change', $('#divABC').find(".quantity"), List.quantityChanged);
And my "List.quantityChanged" event handler happily fires when I update the quanity.
The problem is that when I reference "this" within the event handler, I get the whole document, and not the element that triggered the event.
I have tried to capture the element using syntax similar to:
$(document).on('change', $('#divABC').find(".quantity"), {ctrl: this}, List.quantityChanged);
but when I attempt this, the handler is never fired (even when I change the signature to expect an argument).
Any guidance here would be most appreciated.
Thanks
Griff
Try this:
$('.quantity').live('change', function(){
alert('New value: ' + $(this).val());
});
Pass this to your function:
$(document).on('change', $('#divABC').find(".quantity"), function () {
List.quantityChanged(this);
});

Return Functions using prototype's Event.observe

I'm trying to migrate from using inline event triggers to using event listeners using Prototype's Event.observe function. There are a few inline commands that I don't know how to handle using the function call.
I want to move from:
<form id='formFoo' action='whatever.php' onsubmit="return Foo.verify(this);">
To an event call:
Event.observe('formFoo', 'submit', Foo.verify);
This of course will not work, as I need a return value from the function I call to determine whether the form gets submitted or not.
How do I do this using event handlers?
The easiest way to do this is probably Event.Stop from prototype. This works for me (put this in any script block):
Foo = { verify: function(){ return false } };
Event.observe(window, 'load', function() {
Event.observe('formFoo', 'submit', function(e){
if(! Foo.verify($('formFoo'))){
e.stop();
}
});
});
It stops every form submission; you will just have to change Foo.verify to do what you wanted.
Explanation: When the submit event is triggered, prototype passes the handler a prototype Event object representing the event, and the stop method on that object prevents the submit. The rest is just setting up the event.
Minor note: Among other things, passing Foo.verify directly as a handler will cause verify to be called as a function, not a method (this will be the global object within the call, rather than Foo). That situation might be okay - if verify doesn't use this, you're fine. Be aware of the difference, though.

Resources