Problems in Subscription of global event in JavaScript - javascript

I have the following JavaScript Code, I have some queries on these lines,
what does this lines .events.slice (-1)[0][0] means?
and nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-"; this lines as well?
What does the Subscription of the global events means?
The whole code is too big, but I can post some of the parts of the code, in case it is not understable.
// Subscribe to the global events
var start_from = "0";
if (nodes[GLOBAL_EVENT].events && nodes[GLOBAL_EVENT].events.length > 0) {
start_from = nodes[GLOBAL_EVENT].events.slice(-1)[0][0];
}
nodes_params += "&ns=" + GLOBAL_EVENT + "," + start_from + ",-,-";

1 - events is on array and events.slice(-1) returns the last element in this array, witch seems to be an multidimensional array itself ,and [0][0] returns the first element in the first array.
2 - its a simple string concatenation, += mean appending to the existing variable instead of replacing it
3 - can't say for sure, it depends on what the other codes are

Related

jquery put comma between every variable except last

I have a script that will insert the checked checboxes and radios in the value() of an input tag.
var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
$('#burger-navn').val(burgernavn);
Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them.
Thats the first thing.
Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in.
I hope this is accomplishable.
Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.
var checkedValues = document.getElementsByClassName('checkbox');
Iterate over this array, check for last values. (Check my comments in below code snippet)
var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
//append comma with each value
commaValues += checkedValues[i].concat(",");
}
//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
otherValues = checkedValues[0];
}
//finally concat both strings and put this concated string in input
$('#burger-navn').val(otherValues.concat(commaValues));
So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers
You can do this pretty easy with jQuery $.map.
var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");

JQuery get 'id' attribute

So I have the following code that generates a table and applies a click function to each td within the table. It also applies an incremental id starting with 1. When the user clicks on a td element I'm trying to retrieve the id of the <td> they clicked on. However the value of selector is [object Window]. I'm sure it is something simple but I none of the similar questions on here have helped, and I'm not seeing it.
$("#CMGame").click(function() {
$("#TTTContent").hide();
$("#CMContent").show();
var board = $("#CMBoard");
var htmlString = "";
var count = 0;
for (var i = 0; i < 20; i++) {
htmlString += "<tr>";
for (var i2 = 0; i2 < 20; i2++) {
count++;
htmlString += "<td id='" + toString(count) + "'></td>";
}
htmlString += "</tr>";
}
board.html(htmlString);
$("#CMBoard td").click(function() {
var piece = $(this);
var selector = piece.attr('id');
alert(selector);
/*
if (CMBArray[selector] != 1 OR CMBArray[selector] != 2) {
CMBArray[selector] = 1;
piece.addClass('selected');
}
*/
});
});
There are 2 errors in your code, the td id you create can't be just a number, it has to start with a letter and then you can either remove toString(count) and use only count or change it to count.toString(), which is the correct way.
Here is the specs. for a DOM id:
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
And here for toString():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
The toString is wrong in the code. Change
toString(count)
to
count.toLocaleString()
toString(count) is effectively like saying this.toString() which, in your case basically means window.toString(), which results in [object Window].
Instead, use count.toString().
Here's a quick test:
var count = 0;
console.log('second toString: ' + toString(count) );
console.log('second toString: ' + count.toString );
Bear in mind that, whenever you concatonate strings in Javascript, the toString method is called on all objects by default. For example, these two expressions yield the same output:
var number = 5;
console.log( 'The number is ' + number.toString() );
console.log( 'The number is ' + number );
The toString method you are calling is actually window.toString.
By not specifying a parent object for toString, you are invoking the method on the global window object. That is why you see "[object Window]", it is returning a string representation of the invoking object.
You don't need the toString at all. Javascript cast numberics to a string when you add it to a string.
this.id will return the id of the a jQuery element. E.g.:
$("td").click(function(){
alert(this.id);
});
Your problem is in the event $("#CMGame").click(function()
when try to convert to string with toString(count) javascript and jquery don't understand that they do understand count.toString() here is the source javaScript toString function.
Suggestion about some code you have:
first this one var board = $("#CMBoard"); you pass the html element to a javascript variable for you can do this board.html(htmlString); i think you do that so your function can be more faster than using other method to manipulate the DOM but in this case it look that we are not looking for best performances so other option is keep it simple with this $("#CMBoard").append(htmlString)
The id you set to each element is a number that is not a good practice at all and also there is a suggestion for compatibility for HTML5 to HTML4 look;
Note: Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility. you can find this in global attribute id so is better to set a real id name you can do something like this in your code htmlString += "<td id='item_" + count.toString() + "'></td>";
so the id will come out like id="item_1"

Convert a string with function calls to an array

I need to convert this function call to a simple array[] but it's not working for some reason.
Here's the fiddle
var LongCombinedReady = $('#GeoImageLat').val(exifObject.GPSLatitude + "," + "'" + exifObject.GPSLatitudeRef + "'")
var LatCombinedReady = exifObject.GPSLongitude + "," + "'" + exifObject.GPSLongitudeRef + "'"
//an attemp to take the values and convert them to an array but it doesn't work.
var LongCombined = [LongCombinedReady];
var LatCombined = [LatCombinedReady];
I've commented it all out in the fiddle also here's an image with GeoCoords if you don't have one for testing.
Test Geotag image
Basically I read the images Geotag and then convert the tag from DMS to DD so it can be used for something like Google maps.
There are three problems:
you are missing an apply in line 49
you are applying array with one item being a string while function you are applying to expects four parameters
at line 43 LongCombinedReady is an jQuery object

Javascript unexpected assignment behavior

I'm writing a function to replace all occurrences of variables p and q with their respective values without using eval(), however, I'm running into some unexpected behaviors. BTW, I'm using phpjs for the str_replace
Fiddle: http://jsfiddle.net/5Uedt/2/
function table(str){
str=str_replace(["nand","nor","implies","equals","not","xor","and","or","(",")"],[" 3 "," 4 "," 5 "," 6 "," 7 "," 8 ", " 9 ", " 10 ", " ( "," ) "],str).replace(/\s{2,}/g, ' ').trim();
str=str_replace(["3","4","5","6","7","8", "9", "10", "(",")"],["nand","nor","implies","equals","not","xor","and","or","(",")"],str).split(" ");
var vars={p:1,q:1};
for(vars['p']=1;vars['p']>=0;vars['p']--){
for(vars['q']=1;vars['q']>=0;vars['q']--){
alert(str);
newinput=str;
for(var i=0;i<newinput.length;i++){
var token=newinput[i];
if(token.length===1){
console.log(newinput[i]);
newinput[i]=vars[newinput[i]];
}
}
// console.log(n.join(" "));
}
}
}
I have this code for replacing all occurrences, but it's not working. I'm alerting the original string entered in every time, however, the string changes. The expected output of the function is p,and,q repeated 4 times, instead, I have p,and,q, then 1,and,1 repeated 3 times. However, I don't seem to have any assignments to str. Does anyone know why this is happening?
When you set newinput equal to str, you're still referencing that original object. When you change the value later in newinput you affect the str variable.
If you want to clone the object you can iterate over the properties of str like so:
var newinput = {};
for(var key in str) {
newinput[key] = str[key];
}
Thus making a clone of your original object and you won't be affecting it's values. Assuming you don't have objects you want to clone inside your str object. If you do, just run this function recursively.
Updated Fiddle

Help on eval() function

I need help on this eval() problem:
var ScoreFuncName = 'scoreCondition_' + criteriaName;
var allCheckBox = $('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");
eval(ScoreFuncName + '(' + allCheckBox.length + ')');
The eval() function is evaluating which checkbox is ticked and will do other things accordingly, it worked great in Firefox but not in google Chrome and IE.
Scratching my head for 3 days on how to fix this. Thank you.
You should not be using eval for that.
If the function is in global scope. All you need to do is
window[ScoreFuncName](allCheckBox.length);
It would be better to name space it instead of using a global with window
Eval is not needed to do this. Also take notice that I am calling size on the jQuery object rather than length.
var scoreFunc = this['scoreCondition_' + criteriaName];
var allCheckBox =
$('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");
scoreFunc(allCheckBox.size());
Hm... don't.
There realistically is not a need to use eval in this condition (and I would say that there is no need for a string look-up of the function). Since it looks clear that you have a finite and knowable number of conditions and a finite and knowable number of functions, then you can simply use a switch to actually select a function dynamically:
var toRun; // variable to store the function.
switch(criteriaName)
{
case "criteria1":
// keep the actual function in the variable, not some string.
toRun = function(e){console.log("I is so special! " + e)}
break;
case "criteria2":
toRun = function(e){console.log( e + " is not a squid!" )}
break;
}
var allCheckBox = $('div#'+SubListId).find("input:image[name^='" +
ChkBoxPrefix + "'][value='1']");
// then just call it!
toRun(allCheckBox.length)

Categories

Resources