split window location accordingly - javascript

I am trying to redirect the user according to a lang choice drop down and using their current window.location
So if the user is visiting
xxxx.com will need to go to xxxx.com/langchoice.
2.xxxx.com/currentlang/test.php will need to go to xxxx.com/langchoice/test.php
3 xxxx.com/test.php will need to go to xxxx.com/langchoice/test.php
I have done 1 and 2 but not particularly happy with the way that I coded this considering that if more languages might come I need to add a line every time...can this be rewritten better?
var s = window.location.href;
if (s.indexOf(".php") !=-1)
{
if (s.indexOf("/en/") !=-1)
{
var location=window.location.href.replace("/en/","/"+evt.selectedItem+"/");
}
else if (s.indexOf("/gr/") !=-1)
{
var location=window.location.href.replace("/gr/","/"+evt.selectedItem+"/");
}
else if (s.indexOf("/it/") !=-1)
{
var location=window.location.href.replace("/it/","/"+evt.selectedItem+"/");
}
else
{
}
window.location.replace(location);
}
else
{
var location=window.location.href.replace("#","");
window.location.replace(location+evt.selectedItem);
}

This does make the check to see if there is a "language", but the basic idea to replace would be
There are many ways of doing it, this is one way
var orgPathName = window.location.pathname;
var newPathName = orgPathName.replace(/^\/[^\/]*/,"/" + evt.selectedItem);
var newUrl = window.location.href.replace(orgPathName, newPathName);
Now to do the detection, you do a simple test
var hasLang = (/^\/(en|gr|in)\//i).test(window.location.pathname);
pain with this is maintaining the language list

How do you persist langchoice? Do you store it in a cookie?
I think you are essentially saying that the user should be at:
xxxx.com/[langchoice]etc
at all times.
So you could split on '/' and then, if it exists, check item [1]. If it matches the langchoice cookie, continue, if it doesn't, swap it out.

Related

Execute function if url does not contain a string from array

I'm trying run a script if URL doesn't contain specific string. Here is what i have so far:
var ignorePages = ['page1','page2','page3'];
if (window.location.href.indexOf($.inArray(ignorePages)) === -1) {
// do something
}
But this is not working. I would like to test if the string is found in array and if not, execute. Searched the SO Q/A but couldnt find a solution via array using jQuery's inArray.
You can do this easily with underscore. I also think you may want to use location.pathname instead of location.href. Anyhow, this is how I would do it.
import { contains } from 'underscore';
let blacklist = ['/splash', '/login', '/feed' ];
if (! contains(blacklist, window.location.pathname) {
/* do stuff here */
}
Thanks all for pointing in right directions. I've solved it with correct usage of inArray:
var ignorePages = ['/page1','/page2','/page3'];
var currentUrl = window.location.pathname;
if ($.inArray(currentUrl, ignorePages) === -1) {
// do something
}

Binary Search Tree Syntax

For this portion of an implementation of a binary search tree in JS, what is the significance of referring to "this._root"? (why can't they say "this.root")? The link for this is available at http://www.nczonline.net/blog/2009/06/16/computer-science-in-javascript-binary-search-tree-part-2/
BinarySearchTree.prototype = {
//more code here
remove: function(value){
var found = false,
parent = null,
current = this._root,
childCount,
replacement,
replacementParent;
//make sure there's a node to search
while(!found && current){
//if the value is less than the current node's, go left
if (value < current.value){
parent = current;
current = current.left;
//if the value is greater than the current node's, go right
} else if (value > current.value){
parent = current;
current = current.right;
//values are equal, found it!
} else {
found = true;
}
}
//only proceed if the node was found
if (found){
//continue
}
},
//more code here
};
They may be trying to indicate that this variable should not be accessed outside of the object (private in other languages).
Python has a strong convention of using names starting with underscore character to indicate that this field or method is private. The author may be trying to apply the same convention to javascript.
I suppose that more complete example is located here: https://github.com/nzakas/computer-science-in-javascript/blob/master/data-structures/binary-search-tree/binary-search-tree.js
Regarding this._root - I think it's author's decision only, without any special meaning.

Checking User location every 5 minutes javascript

So I think this solution will work but just wanted to see if there was something a bit more elegant. So I want to allow a user to "check in" to a location and once they have done so I want to see if they have remained in that location. I would check about every 5 minutes. Once they have checked out then I could stop checking. The goal is to get the total time spent at a store. I am using the Javascript SDK for Parse. This is the basic jist of my solution not a complete solution. Using a while loop to check a users location and to continue to do so as long as they remained checked in. Thanks for any suggestion and help! (Also I am using Google maps api to get store location). Just to be sure I am asking more if my approach is correct not if my code is correct.
checkIn: function(){
store_location = "something predefined";
Parse.GeoPoint.current({
success: function(point){
var user_location = new google.maps.LatLng(point.latitude,point.longitude);
if(user_location = store_location){
this.checkedIn();
},
}
});
},
checkedIn: function(){
///run loop while the user is still checked in
///increment total time by 5 min every time loop is called
var checked_in = true;
total_time = 0;
while(checked_in){
setTimeout(function(){
var user_location = new google.maps.LatLng(point.latitude,point.longitude);
if(user_location = store_location){
total_time=total_time + 5
}else{
checked_in = false;
}
}, 3000000)
}
}
window.setInterval(function(){
var user_location = new google.maps.LatLng(point.latitude,point.longitude);
if(user_location = store_location){
total_time=total_time + 5
}else{
checked_in = false;
}
},3000000);
instead of using the while and setTimeout, why dont you use setInterval? i think it is easier and simplify the code

Using eval to assign a variable to a method. How else should I do it?

I am using a method to accept a portion of an element's ID and use that to determine which url path I need to pass to a method. In my case this is used by a click event on a button that could be attached to any one of a number of grids so I need to know which grid I am on in order to know what data to reload:
jQuery('.reset').click(function(e) {
e.preventDefault();
jQuery('#' + grid_id + '_mnf').toggle();
jQuery('#' + grid_id + '_mnfall > .instance').each(function () {
jQuery(this).removeAttr("checked");
});
var url = eval(grid_id + '_url');
jQuery('#foo').setGridParam({url:url}).trigger('reloadGrid');
});
The possible urls are defined as variables so I have something like:
var foo_url = url_path + '?input=moduleone&param=1';
var bar_url = url_path + '?input=moduleone&param=2';
This means that in the setGridParam method above the url value will be one of these vars. If I simply do:
var url = grid_id + '_url'; //note I'm not using eval here
The value passed to setGridParam will not work.
If I don't use eval like I do above the url will not work. Why? What is going on here? What else should I do since "eval is evil"?
In my mind, without using eval, I am passing the url like:
jQuery('#foo').setGridParam({url:foo_url}).trigger('reloadGrid');
but this fails so apparently eval is required here?
Because I am sure this is too rigid and clunky of a way to do this and in case anyone wants to see it (and perhaps suggest how I am doing this wrong?), here is how I am getting that grid_id:
// ex. id='foo_filter'
var source = $(this).parent().parent().attr('id').split('_');
var parsed_source = source.splice(1, source.length + 1);
grid_id_portion = '';
for (var i = 0; i < parsed_source.length; i++) {
grid_id += parsed_source[i];
if(i < parsed_source.length - 1){
grid_id += '_';
}
}
Some issues I see... I have to define the urls as variables for each grid. This is quite inflexible, yes? Those urls are pretty similar as well so defining a bunch of them seems inefficient. Also, what if someone crafts a special chunk of code to insert as the ID that I am breaking apart to pass to eval. That could be bad news, yes? Any suggestions on how to improve on this would be greatly appreciated.
Use a map to store URLs, not local variables.
var URLs = {
foo: url_path + '?input=moduleone&param=1',
bar: url_path + '?input=moduleone&param=2'
};
jQuery('.reset').click(function() {
//do stuff...
var url = URLs[grid_id];
jQuery('#foo').setGridParam({url:url}).trigger('reloadGrid');
});

javascript - coldfusion - working with a list

This is probably easy for someone.
I am returning a list of campaignIDs (12,45,66) via JSON to a javascript variable
var campaignList = res.DATA.CAMPAIGNS
Now, given a specified campaignID passed in the URL
var campaignId ='<cfoutput>#url.campaignID#</cfoutput>'
I want to check if the returned list contains this campaignID
Any help much appreciated.
Plenty of ways to do it, but I like nice data structures, so ...
Split the list on comma, then loop over list, looking for value:
function campaignExists(campaignList,campaignId) {
aCampaignList = campaignList.split(',');
for (i=0;i<aCampaignList.length;i++) {
if (aCampaignList[i]==campaignId)
return true;
}
return false;
}
Since Array.indexOf sadly isn't cross browser, you're looking at something like:
// assume there is no match
var match_found = false;
// iterate over the campaign list looking for a match,
// set "match_found" to true if we find one
for (var i = 0; i < campaignList.length; i += 1) {
if (parseInt(campaignList[i]) === parseInt(campaignId)) {
match_found = true;
break;
}
}
If you need to do this repeatedly, wrap it in a function
Here's a bit of a "out of the box" solution. You could create a struct for your property id's that you pass into the json searilizer have the key and the value the same. Then you can test the struct for hasOwnProperty. For example:
var campaignIDs = {12 : 12, 45 : 45, 66 : 66};
campaignIDs.hasOwnProperty("12"); //true
campaignIDs.hasOwnProperty("32"); //false
This way if the list is pretty long you wont have to loop through all of the potential properties to find a match. Here's a fiddle to see it in action:
http://jsfiddle.net/bittersweetryan/NeLfk/
I don't like Billy's answer to this, variables within the function have been declared in the global scope and it is somewhat over complicated. If you have a list of ids as a string in your js just search for the id you have from user input.
var patt = new RegExp("(^|,)" + campaignId + "(,|$)");
var foundCampaign = campaignList.search(patt) != -1;

Categories