Cycle.js/xstream click event streamed once, but fired twice - cyclejs

There's a single button element on the page and the following click stream:
let submitClick$ = sources.DOM.select(buttonSel)
.events("click")
.mapTo(true)
.debug(console.log)
Once I click on the button, true is logged, which is correct.
However, when I map the stream, the code inside runs twice:
let submitDeal$ = submitClick$.map(() => {
console.log("Clicked")
// ...
})
No other event handlers should be attached to the button, and the element itself sits inside a div:
button(".btn--add", "Submit")
The usual event.preventDefault() and event.stopPropagation() doesn't make a difference, and inspecting the event does show that it is fired from the same element button.btn--add.
Not really sure what's going on, any ideas are appreciated! Thanks!
Versions:
"#cycle/dom": "^12.2.5"
"#cycle/http": "^11.0.1"
"#cycle/xstream-run": "^3.1.0"
"xstream": "^6.4.0"
Update 1: I triple checked and no JS files are loaded twice. I'm using Webpack that bundles a single app.js file that's loaded on the page (Elixir/Phoenix app). Also when inspecting the button in the Event Listeners tab in Chrome's Developer Tools, it seems that only 1 event handled is attached.
Update 2: Gist with the code

Too little information is given to resolve this problem. However some things come to mind:
You shouldn't use .debug(console.log) but .debug(x => console.log(x)) instead. In fact .debug() is enough, it will use console.log internally.
Then, is the button inside a <form>? That may be affecting the events. In general this question needs more details.

Turns out this was due to a bug in xstream, which was fixed in xstream#7.0.0.

Related

Nuxt-link delay transition to new page?

This is a follow up to #1458. I'm looking for some direction on how Nuxt expects this to be handled.
I have a menu. When I click on a nuxt-link in the menu, I want to have time to close the menu before the page transition happens. The thing is, I only want that to happen when you click on the nuxt-link in the menu, not every time I go to a certain route (as the previous issue described using a middlewear on the route).
So there are a few different ways to do this, and I'm curious what the "Nuxt" way is?
The way we currently do this, disable the nuxt-link and capture the click, then do a router.push().
<nuxt-link :to="path" event="disabled" #click.native="delayLoad"/>
// Methods
delayLoad(event) {
this.$store.commit("CLOSE_MENU")
setTimeout(()=>{
this.$router.push(event.target.pathname)
}, 2000)
}
Is this a good idea? I just always have an aversion to hijacking nuxt-link and browser navigation like this. It seems janky.
The other ideas we played with were using a query param on the nuxt-link, and then using that in a middlewear to delay the page transition. That seemed worse to me, because now my URL's have a query param in them that is used for an animation, seems like that is abusing query params. This also triggers the page loading progress bar, which isn't really the intent, it's to have a sequenced animation happen, then page load.
It seems to me that perhaps nuxt-link should have a delay prop, or perhaps the page transition config should allow for a delay (like it does with duration)?
I wanted to do this as well and came up with the following solution. Using the new slots api you can more elegantly customise the nuxt-link behaviour:
<nuxt-link v-slot="{ route, href }" :to="path" custom>
<a :href="href" #click.prevent="$emit('navigate', route)">
<slot></slot>
</a>
</nuxt-link>
This will make the link emit a navigate event with the route as a param. You then listen for this event wherever you include your menu component, like this:
<template>
<transition
name="fade"
#after-leave="maybeNavigate"
>
<MainMenu
v-if="menuIsVisible"
#navigate="navigate"
/>
</transition>
</template>
<script>
export default {
data: () => ({
menuIsVisible: false,
navigateToOnMainMenuClose: null,
}),
methods: {
navigate(route) {
this.navigateToOnMainMenuClose = route
this.menuIsVisible = false
},
maybeNavigate() {
if (this.navigateToOnMainMenuClose) {
this.$router.push(this.navigateToOnMainMenuClose)
this.navigateToOnMainMenuClose = null
}
},
},
}
</script>
Whenever you click a nav link in the menu, the route will be stored and the menu will close. After the menu out animation has finished, maybeNavigate() will push the stored route, if there is one. This removes the need for a setTimeout and if you manage to click multiple links in quick succession only the last one will be stored and navigated to.
Since nuxt-link is essentially a wrapped version of vue's router-link, if you look at the documentation for that there is an event property that accepts string or string[], looking at it's source code here: https://github.com/vuejs/vue-router/blob/dev/src/components/link.js#L86
you can see it will register a listener for disabled in this instance. It may make more sense to pass an empty array so that no event listeners are registered, but that's at the cost of readability.
Otherwise, #click.native is the suggested way to handle custom click handlers for router-link (see: https://github.com/vuejs/vue-router/issues/800#issuecomment-254623582).
The only other concerns I can think of are what happens if you click 2 different links in rapid succession and what happens if you click more than once. May just want to add a variable to track if a link has been clicked to prevent firing setTimeout multiple times, which could navigate you from page A to B and then to C as all timeouts will fire if not canceled. Or maybe you want to only navigate to the 'last' link clicked, so if another link is clicked, you would cancel the earlier setTimeout. This is realistically an edge case that probably won't be an issue, but worth exploring.
Otherwise, IMO, looks good to me. This seems like the simplest way to implement this without having to create a custom component / plugin. I'm no expert, but is likely how I would implement this functionality as well. It would be nice to see a delay option though since I can see myself using that functionality as well with vuetify.
Another potential method would be to do your store commit in beforeTransition: https://nuxtjs.org/api/configuration-transition/
Though I'm not sure that there is access to the store there, so you might have to write a custom plugin for that as well. Again, seems more complicated than it's worth for a simple delayed animation. Simple, working code is sometimes the best solution, even if it's not the most extensible option.
See also: How can I transition between two nuxt pages, while first waiting on a child component transition/animation to finish?
for another way of handling this.

How to override v-on:click in vue for logging purposes

Looking to implement some logging with the purpose of generating some usage statistics for a web application written with Vue.
I want to avoid writing an explicit 'log' statement within or with every 'on click' callback.
Is it possible to wrap/override the v-on:click directive to first perform logging, then execute the callback?
As far as I know it is not possible to do it for all v-on:clicks at the same time. As the event handlers are connected to the specific elements you would need to do it for every element separately.
Instead you can add an eventlistener for click events like this:
window.addEventListener('click', e => console.log(e))
or like this
document.onclick = e => console.log(e)
Note that this will log every single click, even if it's not on an element with v-on. The event here gives you the source element that was clicked, that you might be able to use to define if the click is relevant for your logging or not.
This previous post could work for you:
Extend vueJs directive v-on:click
A wrapper component for you click event elements.

Disable automatic select of node on click?

I'm using a VIS.JS network diagram as a menu (of sorts) with a master/detail relationship to another area of the screen. Each time a user selects a node I signal the loading of the other area. Since the load is asynchronous and can take time (1-2 sec) I'd like to prevent the network node selection from changing until the details are loaded.
Ideally I'd like for the click to invoke the callback, without changing the node selection. Then receive a notification from the detail pane that the loading is complete, and only then change the node selection through code.
I think the only thing I'm missing is the ability to disable the auto-selection of a node when it is clicked.
Is that possible?
Thanks
-John
I don't know if it'll exactly fit your need but,
I needed to create some node unselectable so I prefix my unselectable node's id with a marker.
And then
const unselectableMarker = 'header-';
network.on('selectNode', (opts) => {
network.setSelection({
nodes: opts.nodes.filter(id => !id.startsWith(unselectableMarker)), // prevent selection of headers nodes
edges: opts.edges,
});
});
I've found nothing in actual doc for preventing events in network context.
Capturing the event and preventing default behaviour should not focus the element.
handleClick (evt) {
evt.preventDefault();
// rest of code
}

Win8 JS App: How can one prevent backward navigation? Can't set WinJS.Navigation.canGoBack

Fairly new to developing for Windows 8, I'm working on an app that has a rather flat model. I have looked and looked, but can't seem to find a clear answer on how to set a WinJS page to prevent backward navigation. I have tried digging into the API, but it doesn't say anything on the matter.
The code I'm attempting to use is
WinJS.Navigation.canGoBack = false;
No luck, it keeps complaining about the property being read only, however, there are no setter methods to change it.
Thanks ahead of time,
~Sean
canGoBack does only have a getter (defined in base.js), and it reflects the absence or presence of the backstack; namely nav.history.backstack.
The appearance of the button itself is controlled by the disabled attribute on the associated button DOM object, which in turn is part of a CSS selector controlling visibility. So if you do tinker with the display of the Back button yourself be aware that the navigation plumbing is doing the same.
Setting the backstack explicitly is possible; there's a sample the Navigation and Navigation History Sample that includes restoring a history as well as preventing navigation using beforenavigate, with the following code:
// in ready
WinJS.Navigation.addEventListener("beforenavigate", this.beforenavigate);
//
beforenavigate: function (eventObject) {
// This function gives you a chance to veto navigation. This demonstrates that capability
if (this.shouldPreventNavigation) {
WinJS.log && WinJS.log("Navigation to " + eventObject.detail.location + " was prevented", "sample", "status");
eventObject.preventDefault();
}
},
You can't change canGoBack, but you can disable the button to hide it and free the history stack.
// disabling and hiding backbutton
document.querySelector(".win-backbutton").disabled = true;
// freeing navigation stack
WinJS.Navigation.history.backStack = [];
This will prevent going backward and still allow going forward.
So lots of searching and attempting different methods of disabling the Back Button, finally found a decent solution. It has been adapted from another stackoverflow question.
Original algorithm: How to Get Element By Class in JavaScript?
MY SOLUTION
At the beginning of a fragment page, right as the page definition starts declaring the ready: function, I used an adapted version of the above algorithm and used the resulting element selection to set the disabled attribute.
// Retrieve Generated Back Button
var elems = document.getElementsByTagName('*'), i;
for (i in elems)
{
if((" "+elems[i].className+" ").indexOf("win-backbutton") > -1)
{
var d = elems[i];
}
}
// Disable the back button
d.setAttribute("disabled", "disabled");
The code gets all elements from the page's DOM and filters it for the generated back button. When the proper element is found, it is assigned to a variable and from there we can set the disabled property.
I couldn't find a lot of documentation on working around the default navigation in a WinJS Navigation app, so here are some methods that failed (for reference purposes):
Getting the element by class and setting | May have failed from doing it wrong, as I have little experience with HTML and javascript.
Using the above method, but setting the attribute within the for loop breaks the app and causes it to freeze for unknown reasons.
Setting the attribute in the default.js before the navigation is finished. | The javascript calls would fail to recognize either methods called or DOM elements, presumably due to initialization state of the page.
There were a few others, but I think there must be a better way to go about retrieving the element after a page loads. If anyone can enlighten me, I would be most grateful.
~Sean R.

What's the difference between .select, .show, and .load in jquery-ui tabs?

I see that there are three events fired when a tab is selected and I see the order in which the events are fired but I'm rather confused about which event to use or how these are truly different. If all three are fired, couldn't I just put my code in any of the events?
I must be missing something here. Can someone clarify?
So after messing with this more I'm going to share what I ended up doing in the hopes that it might help someone else.
I had to generate dynamic tabs based on data returned in an Ajax call. It's basically data by date where the tabs are the date and they display whatever data falls within that date.
Generating the tabs from the returned data was easy but I couldn't figure out how to write out the associated data. Finally (and I should have started here), I looked that the generated dom and noticed that a dynamically created tab also creates a div. Maybe that's obvious to some (it wasn't to me) and if it was in the documentation I missed it. Anyway, this code will generate tabs from an array and then append html to the associated div when the tab is clicked. I don't need all the variables but I thought that might make it more readable. Put the function for show before adding the tabs or it wont work!
var _sessionDates = getSessionDates(sessionData.Sessions);
var $tabs = $("#sub-tabs");
$tabs.tabs({
show: function(event, ui) {
var selected = $tabs.tabs('option', 'selected');
var _sessionDates = getSessionDates(sessionData.Sessions);
var grid = buildGrid(_sessionDates[selected]);
$('#' + _sessionDates[selected]).html(grid);
}
});
$(_sessionDates).each(function(i, dayOfShow) {
var d = dateFormat(dayOfShow, "mediumDate");
$tabs.tabs('add', '#' + dayOfShow, d);
});
Finally, I have to "scroll" through my data shown in the tab and I was able to do that with these two lines. The first line gives me the id of the div element corresponding to the selected tab (which is really the important part) and the second line just calls my method and passes in the id of the div less the '#'. My date is also my id. There's a global variable that I've changed outside of this that makes it work. I know that's bad and I'll remove it when I refactor it.
var $el = $($('#sub-tabs a')[$('#sub-tabs').tabs('option', 'selected')]).attr('href');
$($el).html(buildGrid($el.replace('#', '')));
select is triggered when a tab is clicked on, but before the tab has been shown
load is triggered after the contents of a remote tab have been loaded (i.e. a tab whose content is not part of the initial page payload, but that is loaded via an ajax call when the user clicks on the related tab)
show is triggered after a tab has been shown
The jQuery documentation makes this relatively clear, but I had to experiment in order to fully understand the difference between select and show.
This has been made more clear since the original question was asked so now the following is true:
Effectively, the functionality for "show" is now provided by "activate" and "select" is done with "beforeActivate" while "load" is still the same.
activate: (previously show) Triggered after a tab has been activated (after animation completes)
beforeActivate: (previously select) Triggered immediately before a tab is activated.
load: Triggered after a remote tab has been loaded.
Also provided are:
beforeLoad: Triggered when a remote tab is about to be loaded, after the beforeActivate event.
create: Triggered when the tabs are created.