Javascript line breaking in IE8 - javascript

I have a script which is using this line as part of some geocoding.
var dms = String(dmsStr).trim().replace(/^-/,'').replace(/[NSEW]$/i,'').split(/[^0-9.,]+/);
It works fine in all browsers apart from IE, which is kicking out an error.
I'm sending it parameters.
0.5501039994056782
It's not my code I'm just debugging it. I'm assuming it could be a problem with Typecasting it to a string, given that it's clearly a number.
But I'd love some feedback.

There is no String.trim() in IE8. You can add it like this:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
as per this answer.

I don't think IE has trim(). Try this:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
See this SO question for more information

the exact error is
"Object doesn't support property or method 'trim'"
so to solve you could do:
var dms = jQuery.trim(String(dmsStr)).replace(/^-/,'').replace(/[NSEW]$/i,'').split(/[^0-9.,]+/);

Related

Why does my Javascript break in IE8?

The following code breaks in IE8:
getTypes: function (filter) {
features = []
_.each(this.collection.models, function (item) {
_.each(item.get(filter), function (value) {
if(features.indexOf(value) == -1){ //// error happens here
features.push(value)
}
})
})
return features
}
I get the error message:
Message: Object doesn't support this property or method
http://jsfiddle.net/w8fm2bf1/
Why is this?
The IE versions before IE9 does not support .indexOf() function for Array
As an alternative you can use jQuery.inArray(). Something like this:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(val) {
return jQuery.inArray(val, this);
};
}
Array.prototype.indexOf isn't supported in IE until version 9. (source).
You'll need to monkey patch it (there's an example on the MDN page linked above) or use an alternative.

How do I verify if several attributes are in a JSON structure within JavaScript?

I am creating a module that takes in several complicated JSON files and would like some code to give the user feedback if certain elements are absent.
Below is the way I am doing it now, but I cannot help to think there must be a cleaner, less hacky way.
var _und = require("underscore");
//this function takes a list of required attributes and ensures they are present
var check_req_attr = function(config, req_attr, callback) {
var config_attr = Object.keys(config);
var absent_attr = _und.difference(req_attr, config_attr); //slightly hacky code that checks to ensure config has correct vars
if (absent_attr.length !== 0) {
throw Error("missing following attributes from config:" + absent_attr);
} else {
callback();
};
};
It just feels...dirty. If there is no real elegant way to do it, I would be open to critiques on my code. Thanks!
Parse the JSON to JS.
var data = JSON.parse(theJson);
Use something like:
function hasKey(obj, key) {
return typeof obj[key] !== 'undefined';
};
function hasKeys(obj, keys) {
for (var i = 1, len = keys.length; i < len; i++) {
if (!hasKey(obj, keys[i])) {
return false;
};
};
return true;
};
Now you can simply do:
if (hasKeys(data, ["firstKey", "secondKey", "thirdKey"]) {
console.log("valid");
};
This should be the way to do it, using every and has:
if (_und.every(req_attr, function(attr) {
return _und.has(config, attr);
}))
throw new Error();
In a native environment, you would just use the in operator:
req_attr.every(function(attr){ return attr in config; })
I think your solution is actually quite elegant! No need for an anonymous function, and the loop (which must happen at some point, obviously) neatly abstracted away with difference.
Two suggestions:
I'd give the function a synchronous signature. No callback argument. There can't be any reason to go async if you honor the function signature (i.e. basing your answer on config and req_attr only).
I'd change the function to return the missing properties (attributes is wrong term). You could also add a requireProperties function that uses this "check" function that would throw if a property was missing. This allows for different kind of uses.
Why don't you try with something like:
obj = JSON.parse(json);
and then check
if(obj.YourProperty == undefined){
//do something..
}
Hope i understood your question.. It should work with complicated JSON files too.. Good luck ;)
You could also use the in operator (requiredAttr in obj):
function objHasAllRequiredAttrs(obj, attrNames) {
return attrNames.reduce(function(memo, attrName) {
return memo && (attrName in obj);
}, true);
}
objHasAllRequiredAttrs({foo:1}, ['foo']); // => true
objHasAllRequiredAttrs({bar:1}, ['foo']); // => false

Testing the existence of a method

I'm trying to make some existing JS backwards compatible. I need to override a method if it does not exist, otherwise just return the existing method.
Here is the code I have so far:
this.grid.getDataSource = function(){
if (getDataSource == undefined)
return getStore();
else
return getDataSource();
}
However it keeps returning an error on the "if" line:
getDataSource is undefined
What is the best way of going about this?
This should work without throwing an error.
if (typeof getDataSource != "function")
you might need to wrap it in a typeof() function
this.grid.getDataSource = function(){
if (typeof getDataSource == undefined)
return getStore();
else return getDataSource();
}
this.grid.getDataSource = getDataSource || getStore;
Here is a nice resourse, which should answer to your question. It's a pretty simple function.
http://phpjs.org/functions/method_exists:471

JavaScript getter for all properties

Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.
My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.
The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.
Proxy can do it! I'm so happy this exists!! An answer is given here: Is there a javascript equivalent of python's __getattr__ method? . To rephrase in my own words:
var x = new Proxy({}, {
get(target, name) {
return "Its hilarious you think I have " + name
}
})
console.log(x.hair) // logs: "Its hilarious you think I have hair"
Proxy for the win! Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
You can combine proxy and class to have a nice looking code like php:
class Magic {
constructor () {
return new Proxy(this, this);
}
get (target, prop) {
return this[prop] || 'MAGIC';
}
}
this binds to the handler, so you can use this instead of target.
Note: unlike PHP, proxy handles all prop access.
let magic = new Magic();
magic.foo = 'NOT MAGIC';
console.log(magic.foo); // NOT MAGIC
console.log(magic.bar); // MAGIC
You can check which browsers support proxy http://caniuse.com/#feat=proxy.
The closest you can find is __noSuchMethod__ (__noSuchMethod__ is deprecated), which is JavaScript's equivalent of PHP's __call().
Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.
var foo = {
__noSuchMethod__ : function(id, args) {
alert(id);
alert(args);
}
};
foo.bar(1, 2);
Javascript 1.5 does have getter/setter syntactic sugar. It's explained very well by John Resig here
It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).
If you really need an implementation that works, you could "cheat" your way arround by testing the second parameter against undefined, this also means you could use get to actually set parameter.
var foo = {
args: {},
__noSuchMethod__ : function(id, args) {
if(args === undefined) {
return this.args[id] === undefined ? this[id] : this.args[id]
}
if(this[id] === undefined) {
this.args[id] = args;
} else {
this[id] = args;
}
}
};
If you're looking for something like PHP's __get() function, I don't think Javascript provides any such construct.
The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each.
In dodgy pseudo-ish code:
for (o in this) {
if (this.hasOwnProperty(o)) {
this['get_' + o] = function() {
// return this.o -- but you'll need to create a closure to
// keep the correct reference to "o"
};
}
}
I ended up using a nickfs' answer to construct my own solution. My solution will automatically create get_{propname} and set_{propname} functions for all properties. It does check if the function already exists before adding them. This allows you to override the default get or set method with our own implementation without the risk of it getting overwritten.
for (o in this) {
if (this.hasOwnProperty(o)) {
var creategetter = (typeof this['get_' + o] !== 'function');
var createsetter = (typeof this['set_' + o] !== 'function');
(function () {
var propname = o;
if (creategetter) {
self['get_' + propname] = function () {
return self[propname];
};
}
if (createsetter) {
self['set_' + propname] = function (val) {
self[propname] = val;
};
}
})();
}
}
This is not exactly an answer to the original question, however this and this questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did.
Coming from Python, what I was looking for was an equivalent of obj.__getattr__(key)and obj.__hasattr__(key) methods. What I ended up using is:
obj[key] for getattr and obj.hasOwnProperty(key) for hasattr (doc).
It is possible to get a similar result simply by wrapping the object in a getter function:
const getProp = (key) => {
const dictionary = {
firstName: 'John',
lastName: 'Doe',
age: 42,
DEFAULT: 'there is no prop like this'
}
return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]);
}
console.log(getProp('age')) // 42
console.log(getProp('Hello World')) // 'there is no prop like this'

Tell if a Javascript function is defined by looking at self[name] - is this a good way?

This is a follow up question to This Question.
I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:
function exist(sFN) {
if(self[sFN]) return true;
return false;
}
It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?
Try this:
function exist(sFN) {
return (typeof sFN == 'function');
}
Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true.
As others have said, you can use typeof, or instanceof to see if it's actually a function.
Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.
just use typeof.
typeof(foobar) // -> undefined
typeof(alert) // -> function
You can't, however, defined a function based on typeof, because you'd need to pass an identifier which might not exist. So if you define function isfun(sym) { return typeof(sym) }, and then tried calling isfun(inexistent), your code would throw.
The fun thing about typeof is that it's an operator, not a function. So you can use it to check a symbol that's not defined without throwing.
if you assume a function in the global scope (i.e., not within a closure), you can define a function to check it as follows:
function isfun(identifier) {
return typeof(window[identifier]) == 'function';
}
Here you pass an string for the identifier, so:
isfun('alert'); // -> true
isfun('foobar'); // -> false
closure?
Here's an example of a function defined within a closure. Here, the printed value would be false, which is wrong.
(function closure() {
function enclosed() {}
print(isfun('enclosed'))
})()
FYI: There is (or was) a nice pitfall for typeof.
FF2 returns 'function' for typeof(/pattern/).
FF3, IE7, and Chrome all return 'object' for the same code.
(I can't verify other browsers.)
Assuming everyone that used FF2 has upgraded, you're in the clear.
But, that's probably a far-fetched assumption.
You can't really wrap this in a method, but it's so simple there is really no need.
function bob()
{}
if( typeof bob == "function" )
alert( "bob exists" );
if( typeof dave != "function" )
alert( "dave doesn't" );
Object.prototype.toString.apply(value) === '[object Function]'
I read somewhere (here and here) that functions are properties of the window object, so you can do the following:
if (window.my_func_name) {
my_func_name('tester!');
}
or for popups:
if (window.opener.my_func_name) {
my_func_name('tester!');
}
A complete solution then:
function function_exists(func_name) {
var eval_string;
if (window.opener) {
eval_string = 'window.opener.' + func_name;
} else {
eval_string = 'window.' + func_name;
}
return eval(eval_string + ' ? true : false');
}

Categories