How to check which subclass is the event fired? - dart

I know event.type in DOM. I can parse for example mouseup, keydown, touchstart and so on. But how can I check for the event subclass? Like MouseEvent, AnimationEvent or ClipboardEvent? Can I use the event.type property?

You can check the class like
void myHandler(Event e) {
if(e is MouseEvent) {
print('Mouse');
} else if(e is AnimationEvent) {
print('Animation');
} else if(e is KeyboardEvent) {
print('Keyboard');
}
}

Since JavaScript is a prototype-based language you can to do it a bit strangely using Object.prototype.toString.call() and then cleaning up the result a little, like this:
var button = document.getElementById("testEvent");
button.onclick = function(e) {
console.log(
Object.prototype.toString.call(e).replace(/^\[object ([^\]]*)\]/, "$1")
);
}
This fiddle shows it in action - http://jsfiddle.net/SrmGJ/1/ working for me in FireFox. It should output "MouseEvent" in the fiddle, but if you hook it up to some of the other events, you will see different results.
Another method would be to call EventType.prototype.isPrototypeOf(e) for each of the types:
...
if (MouseEvent.prototype.isPrototypeOf(e)) { console.log("MouseEvent"); }
if (AnimationEvent.prototype.isPrototypeOf(e)) { console.log("AnimationEvent"); }
if (KeyboardEvent.prototype.isPrototypeOf(e)) { console.log("KeyboardEvent"); }
...
But that would look pretty nasty IMHO.

Related

Dart streams error with .listen().onError().onDone()

I have an issue with some code that looks like this. In this form I have an error
The expression here has a type of 'void', and therefore can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.dart(use_of_void_result).
If I remove the .onDone() the error goes away. Why? ELI5 please :-)
I was looking at https://api.dart.dev/stable/2.7.0/dart-async/Stream/listen.html but seem to still be misundertanding something.
I also read https://api.dart.dev/stable/2.7.0/dart-async/StreamSubscription/onDone.html
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
}).onError((error) {
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
}).onDone(() {
isSaveInProgress = false;
});
Your code is almost right, but will only require a simple change to work correctly.
You would be seeing the same error if you swapped the ordering of onError and onDone, so the issue has nothing to do with your stream usage. However, you're attempting to chain together calls to onError and then onDone which won't work since both of these methods return void.
What you're looking for is cascade notation (..), which will allow for you to chain calls to the StreamSubscription returned by listen(). This is what your code should look like:
serviceName.UploadThing(uploadRequest).listen((response) {
uploadMessageOutput = response.message;
if (response.uploadResult) {
showSuccess();
} else {
showError();
}
getUploadFileList(event);
isSaveInProgress = false;
})..onError((error) { // Cascade
isSaveInProgress = false;
_handleFileUploadError(uploadRequest, error);
})..onDone(() { // Cascade
isSaveInProgress = false;
});

How can I detect a zoom end?

Is there a good way to detect when the map's zoom animation has ended? OpenLayers used to raise the 'zoomend' event after the zoom had completed, but OpenLayers 3 doesn't have a corresponding event. I'm currently using the following approach, but it seems kludgy and brittle at best.
function main() {
var map = ...;
map.getView().on('change:resolution', handleResolutionChange);
}
function handleResolutionChange() {
var map = ...;
map.once('moveend', handleMoveEnd);
}
function handleMoveEnd() {
setTimeout(handleZoomEnd, 0);
}
function handleZoomEnd() {
//Handle the 'Zoom end' event
}
did you try the moveend event on its own???? I have not try it but it should rise on zoomend as well. Also the 'change:resolution' event is not documented. Does it really work??
try the following
var ghostZoom = map.getView().getZoom();
map.on('moveend', (function() {
if (ghostZoom != map.getView().getZoom()) {
ghostZoom = map.getView().getZoom();
console.log('zoomend');
}
}));
I know this question has been a while. I just want to share my idea.
let isMapResolutionChanged;
map.getView().on('change:resolution', () => {
isMapResolutionChanged = true;
});
map.on('moveend', () => {
if (isMapResolutionChanged) {
console.log('fire moveend + zoomend')
}
});
Just wanted to share my solution because I stumbled over the same problem:
let zoomend = function(evt) {
alert('zoomend on resolution: ' + evt.map.getView().getResolution());
evt.map.once('moveend', function(evt) {
zoomend(evt);
});
};
map.getView().once('change:resolution', function(evt) {
map.once('moveend', function(evt) {
zoomend(evt);
});
});
Here the change:resolution event is only fired once at the beginning of a zoom action and is activated again when its finished.
You can have a look at a working fiddle.

Lightbox2 Swipe gesture for touchscreens

To my great surprise Lightbox2(http://lokeshdhakar.com/projects/lightbox2/) does not support swipe gestures out of the box...
I was not able to find any add on in order to support this behavior. Anyone has any suggestions a side from changing the entire plugin? :)
To summary, you must hide the navigation buttons and implement swiping, moving and sliding effect on the image.
You will need :
jquery.event.move
jquery.event.swipe
jquery ui slide effect, you can package it in the jquery ui download builder
maybe there's a simplest way to get/implement all of these 3 small dependencies... but that way works for me.
in the lightbox script, add a new LightboxOptions enableSwipeOnTouchDevices and set it to true :
this.enableSwipeOnTouchDevices = true;
add the following blocks after the this.$lightbox.find('.lb-next').on('click'... block to create the swiping events:
this.$lightbox.find('.lb-image').on("swiperight",function() {
$('.lb-image').effect("slide", { "direction" : "right", "mode" : "hide"} ,function(){
if (self.currentImageIndex === 0) {
self.changeImage(self.album.length - 1);
} else {
self.changeImage(self.currentImageIndex - 1);
}
})
});
this.$lightbox.find('.lb-image').on("swipeleft",function() {
$('.lb-image').effect("slide", { "direction" : "left", "mode" : "hide"} ,function(){
if (self.currentImageIndex === self.album.length - 1) {
self.changeImage(0);
} else {
self.changeImage(self.currentImageIndex + 1);
}
})
});
and rewrite the updateNav function like this to hide the navigation buttons:
Lightbox.prototype.updateNav = function() {
// Check to see if the browser supports touch events. If so, we take the conservative approach
// and assume that mouse hover events are not supported and always show prev/next navigation
// arrows in image sets.
var alwaysShowNav = false;
var enableSwipe = false;
try {
document.createEvent("TouchEvent");
alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices)? true: false;
enableSwipe = (this.options.enableSwipeOnTouchDevices)? true: false;
} catch (e) {}
//if swiping is enable, hide the two navigation buttons
if (! enableSwipe) {
this.$lightbox.find('.lb-nav').show();
if (this.album.length > 1) {
if (this.options.wrapAround) {
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
}
this.$lightbox.find('.lb-prev, .lb-next').show();
} else {
if (this.currentImageIndex > 0) {
this.$lightbox.find('.lb-prev').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-prev').css('opacity', '1');
}
}
if (this.currentImageIndex < this.album.length - 1) {
this.$lightbox.find('.lb-next').show();
if (alwaysShowNav) {
this.$lightbox.find('.lb-next').css('opacity', '1');
}
}
}
}
}
};
I've used jquery mobile to detect swipeleft and swiperight. Then bind them to click .lb-next and .lb-prev. It's working now.
Here is my codepen.
PEC's solution worked for me with one modification on a Jekyll site.
Instead of:
this.enableSwipeOnTouchDevices = true;
We added this to /_includes/scripts.html after the dependencies and lightbox.js:
<script>
lightbox.option({
'enableSwipeOnTouchDevices': true,
})
</script>
The PEC solution is good, but it doesn't work anymore with the current version of lightbox (2.11.2). The effect() method doesn't exists anymore.
So the swiping methods should be updated:
this.$lightbox.find('.lb-image').on("swiperight",function() {
if (self.currentImageIndex === 0) {
self.changeImage(self.album.length - 1);
} else {
self.changeImage(self.currentImageIndex - 1);
}
return false;
});
this.$lightbox.find('.lb-image').on("swipeleft",function() {
if (self.currentImageIndex === self.album.length - 1) {
self.changeImage(0);
} else {
self.changeImage(self.currentImageIndex + 1);
}
return false;
});
Less fancy, but shorter and works.
In short: 'catch' swipe gesture and then trigger 'click' on next/prev button based on swipe direction.
let touchstartX = 0;
let touchendX = 0;
function handleGesture() {
if (touchendX < touchstartX) $(".lb-prev").trigger("click");
if (touchendX > touchstartX) $(".lb-next").trigger("click");
}
$(document).on("touchstart", ".lb-nav", e => {
touchstartX = e.changedTouches[0].screenX;
});
$(document).on("touchend", ".lb-nav", e => {
touchendX = e.changedTouches[0].screenX;
handleGesture();
});

Is my implementation of unloaders proper?

I was re-reading this post here: https://stackoverflow.com/a/24473888/1828637
And got concerned about if I did things correctly. This is how I do unloading:
So I set up some stuff per window. And unload them on shutdown. (i dont unload on window close, i havent found a need to yet, as when it closes, everything i added to it goes with with the close [such as my mutation observers]).
All code below is theoretical, the mutation stuff is example, so there might be typos or bugs in it. I was wondering if the idea behind it is appropriate:
var unloadersOnShutdown = [];
var unloadersOnClose = [];
function startup() {
let DOMWindows = Services.wm.getEnumerator(null);
while (DOMWindows.hasMoreElements()) {
let aDOMWindow = DOMWindows.getNext();
var worker = new winWorker(aDOMWindow);
unloadersOnShutdown.push({DOMWindow: aDOMWindow, fn: worker.destroy});
}
}
function shutdown() {
Array.forEach.call(unloadersOnShutdown, function(obj) {
//should probably test if obj.DOMWindow exists/is open, but just put it in try-ctach
try {
obj.fn();
} catch(ex) {
//window was probably closed
console.warn('on shutdown unlaoder:', ex);
}
});
}
function winWorker(aDOMWindow) {
this.DOMWindow = aDOMWindow;
this.init();
}
winWorker.prototype = {
init: function() {
this.gMutationObserver = new this.DOMWindow.MutationObserver(gMutationFunc.bind(this));
this.myElement = this.DOMWindow.querySelector('#myXulEl');
this.gMutationObserver.observe(this.myElement, gMutationConfig);
if (this.DOMWindow.gBrowser && this.DOMWindow.gBrowser.tabContainer) {
this.onTabSelectBinded = this.onTabSelect.bind(this);
this.gBrowser.tabContainer.addEventListener('TabSelect', this.onTabSelectBinded, false);
}
},
destroy: function() {
this.gMutationObserver.disconnect();
if (this.onTabSelectBinded) {
this.gBrowser.tabContainer.removeEventListener('TabSelect', this.onTabSelectBinded, false);
}
},
onTabSelect: function() {
console.log('tab selected = ', thisDOMWindow.gBrowser.selectedTab);
}
};
var windowListener = {
onOpenWindow: function (aXULWindow) {},
onCloseWindow: function (aXULWindow) {
var DOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
for (var i=0; i<unloadersOnClose.length; i++) {
if (unloadersOnClose.DOMWindow == DOMWindow) {
try {
unloadersOnClose.fn();
} catch(ex) {
console.warn('on close unloader:', ex);
}
unloadersOnClose.splice(i, 1);
i--;
}
}
},
onWindowTitleChange: function (aXULWindow, aNewTitle) {},
}
I think one problem is me not using weak references with DOMWindows but I'm not sure.
The idea around unloaders in general seems to be OK, but very limited (to windows only).
The implementation is lacking. E.g. there is a big, fat bug:
unloadersOnShutdown.push({DOMWindow: aDOMWindow, fn: worker.destroy});
// and
obj.fn();
// or
unloadersOnClose.fn();
This will call winWorker.prototype.destroy with the wrong this.
The i++/i-- loop also looks, um... "interesting"?!
Also, keep in mind that there can be subtle leaks, so you should mind and test for Zombie compartments.
Not only can a window leak parts of your add-on (e.g. bootstrap.js) but it is also possible to leak closed windows by keeping references in your add-on. And of course, it's not just windows you need to care about, but also e.g. observers, other types of (XPCOM) listeners etc.

How do I detect a first-run in Firefox a addon?

I would like to know the simplest way to detect a first-run in a Firefox addon. I prefer not to use the (SQLite) Storage API as this seems way overkill for this simple usecase.
I guess my question could also be: what is the simplest way to store a flag?
There you go: http://mike.kaply.com/2011/02/02/running-add-on-code-at-first-run-and-upgrade/
var firstrun = Services.prefs.getBoolPref("extensions.YOUREXT.firstrun");
var curVersion = "0.0.0";
if (firstrun) {
Services.prefs.setBoolPref("extensions.YOUREXT.firstrun", false);
Services.prefs.setCharPref("extensions.YOUREXT.installedVersion", curVersion);
/* Code related to firstrun */
} else {
try {
var installedVersion = Services.prefs.getCharPref("extensions.YOUREXT.installedVersion");
if (curVersion > installedVersion) {
Services.prefs.setCharPref("extensions.YOUREXT.installedVersion", curVersion);
/* Code related to upgrade */
}
} catch (ex) {
/* Code related to a reinstall */
}
}
Maybe a better solution would be:
/**
* Check if this is the first run of the addon
*/
function checkFirstRun(){
if(ss.storage.firstRun == undefined){
ss.storage.firstRun = false;
return true;
}
else{
return false;
}
}

Resources