I'm new to JavaScript and a little bit confused with the duck typing concept. As far as I can tell, I understood the concept. But that leads to a strange consequence in my thoughts. I will explain with the following example:
I'm currently working on a mobile web app with jQuery Mobile. At one point I capture the vmousedown event for a canvas. I'm interested in the pressure of the touch. I found the Touch.webkitForce property.
$('#canvas').live('vmousedown', function(e){
console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}
This works fine when using the Remote Debugging for Chrome. But throws an exception when testing in Opera Firefly, because the originalEvent property is no touch event, but a click event.
So every time I access a property of an object which is not under my authority, do I have to check existence and type?
if( e.originalEvent &&
e.originalEvent.originalEvent &&
e.originalEvent.originalEvent.touches &&
e.originalEvent.originalEvent.touches[0] &&
e.originalEvent.originalEvent.touches[0].webkitForce) {
console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
}
Can please someone clarify that for me?
So every time I access a property of an object which is not under my authority, do I have to check existence and type?
Yes you will have to check the whole path, once at a time, or you can automate it:
function deepObject(o, s) {
var ss = s.split(".");
while( o && ss.length ) {
o = o[ss.shift()];
}
return o;
}
var isOk = deepObject(e, "originalEvent.originalEvent.touches.0.webkitForce");
if ( isOk ) {
// isOk is e.originalEvent.originalEvent.touches.0.webkitForce;
}
Test case:
var o = {
a: {
b: {
c: {
d: {
e: {
}
}
}
}
}
}
var a = deepObject(o, "a.b.c");
var b = deepObject(a, "d");
console.log(a); // {"d": {"e": {}}}
console.log(b); // {"e": {}}
console.log(deepObject(o, "1.2.3.3")); // undefined
Use try catch
$('#canvas').live('vmousedown', function(e) {
try {
console.log(e.originalEvent.originalEvent.touches[0].webkitForce);
} catch(e) {
console.error('error ...');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With