How is page.trendDescriptions = {}; work in the given piece of code? - javascript

I got code from http://cektkp.com/twittermarquee/twitmarquee.js to use a twitter style ticker:
<script type=\"text/javascript\">
//<![CDATA[
var page={};
$(function() {new FrontPage().init()});
//]]>
</script>
I understand there is an anonymous javascript function which creates an instance of FrontPage class and init's it. And var page={}; is an object literal, but is it correct to define it here as first line of the script tag?
I found this in a JS tutorial, You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
Also, in my javascript file I have the following code:
Drupal.behaviors.stocksTicker = {
attach: function( context, settings ) {
page.trendDescriptions = {};
loadTrendDescriptions();
}
}
.
.
.
var processSummizeInternal = function (B) {
var J = page.trendDescriptions[page.query];
.
.
.
function loadTrendDescriptions() {
$("#trends a").each(function () {
var A = $(this);
var C = A.parent().find("em");
if (C.length) {
var B = A.text();
var D = C.text().replace(new RegExp(B.replace(/([^\w])/gi, "\\$1"), "gi"), "<strong>" + B + "</strong>");
var E = A.attr("title").length ? A.attr("title") : A.attr("name");page.trendDescriptions[E] = [B, D]
}
})
}
I'm not able to understand how is js accessing this variable page.? There is no other reference of page anywhere else in any other file.

Is it correct to define it here as first line of the script tag?
You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
This quotation does target constructs like
{init: function(){/* do something*/}}.init();
where really the statement begins with an object literal. Pretty odd? Yes, you would never use such code anyway. In your case,
var page = {};
the object literal is inside the assignment statement. No problems here, it's totally fine.
I'm not able to understand how is js accessing this variable page.?
Then it will automatically refer to a global variable. And you actually even have defined such one in your first snippet, and initialised it to an empty object. The external js you included then defined a trendDescriptions property on it and accessed it happily a few times.

Related

method plugin doesn't work within Function Constructor

What I'm trying to achieve in JavaScript is to make a method of the plugin I'm working with (called "Plugin") flexible. The plugin runs in an iFrame and has cross-domain trust settings applied. I want to use variables to build the method parameter rather than hard code it.
The hardcoded version is shown below and I've double checked this works. I've used it in functions and in a Function constructor. Both work.
window.Plugin.Session.Tags({
TagName: 'SomeTagName',
TagValueTagging: 'sometagvalue; secondtagvalue',
TagValueTaggingReset: '*'
}).Update();
My objective is to replace the 'sometagvalue' with a variable, so I can set the tag dynamically. The help says the parameter is a constant JSON string.
I've tried the following things:
build the parameter as string. Result: Though myText holds the exact same string as in the hardcoded version, the method is not executed.
var myTag = '\\'DEELNEMER ; name\\' ';
var myText = "{TagName : 'Workflow'," +
" TagValueTagging : " + myTag +
", TagValueTaggingReset : '*'}";
alert("myText = " + myText);
x = window.Plugin.Session.Tags(myText);
x.Update();
2) using new Function constructor. I created a variable with the session object and inserted that as parameter. In order to proof myself that I working with the right object, I've put it's LID in an alert as well outside as inside the constructor. Result: the Session.LID was the same inside and outside the constructor, but tagging did not happen.
var myFunction = "alert(\"in constructor Session.LID = \" + prmSession.LID); window.addTag =
prmSession.Tags({TagName : \'Workflow\', TagValueTagging : \'DEELNEMER\' , TagValueTaggingReset :
\'*\'}); window.addTag.Update();"
var addTagFunction = new Function("prmSession", myFunction)
var prmSession = window.Plugin.Session;
alert("in main function Session.LID = " + prmSession.LID);
addTagFunction(prmSession);
3) using JSON stringify. Again Result: Tag was not set, in neither variant..
var myTag = 'DEELNEMER ; name ';
var obj = new Object();
obj.TagName = "Workflow";
obj.TagValueTagging = myTag;
obj.TagValueTaggingReset = "*";<br/>
var myJSON= JSON.stringify(obj);
Plugin.Session.Tags(myJSON).Update();<br/>
/*variant 2*/<br/>
var myObjParsed = JSON.parse(myJSON);
Plugin.Session.Tags(myObjParsed).Update();
I would be very greatful for a tip how to solve this issue.
Regards
Plugin appears to translate the javascript into backend data queries during the compilation of the solution.
The use of parameters is therefore not possible.

Dynamically Select Variable [duplicate]

This question already has answers here:
Access value of JavaScript variable by name?
(7 answers)
Closed 5 years ago.
I have 2 variables like so
var variable_1 = "foo";
var variable_2 = "bar";
I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.
$("input:checked").each(function() {
$(div).append('variable_'+$(this).val());
}
So I'd concatenate the text 'variable_' with the value of each checkbox.
Thanks!
You can use eval to get any variable values dynamically.
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
$(div).append(eval('variable_'+$(this).val()));
}
Note: it's not the best solution because eval has some security issues as well.
Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.
This one is a ternary if:
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
var isChecked = $(this).is(':checked');
var append = (isChecked) ? variable_1 : variable_2;
$(div).append(append);
}
Alternatively you could use a switch statement for multiple values.
If the variables are globals then you can use
var y = window["variable_" + x];
to read or
window["variable_" + x] = y;
to write to them dynamically.
Better practice however is to use an object to store them instead of using separate variables...
var data = { variable_1: null,
variable_2: null };
...
y = data["variable_" + x];
Javascript can also use eval to access dynamically variables, amazingly enough even local variables
function foo(s) {
var x = 12;
return eval(s);
}
console.log(foo("x"));
and even more amazingly this allows the dynamic creation of new local variables...
var y = 42;
function foo(s) {
var x = 1;
eval(s);
return y; // may be global y or a local y defined by code in s
}
foo("x") // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).
Create object with properties and access that properties via obj['prop'] notation, see code below:
var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
$("input:checked").each(function() {
var dynamicVariableName = 'variable_' + $(this).val()
var dynamicVarValue = myObj[dynamicVariableName];
$(div).append(dynamicVar);
}
If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

Javascript + and string return value from function?

This is a stupid noob issue that just pisses me off .. sorry.
This works: alert('hello');
This works: alert(getsomestring());
This works: alert('hello'+'goodbye')
So why doesn't this work: alert('hello'+getsomestring());
I tried these with no luck:
alert('hello'+getsomestring(););
alert('hello'+getsomestring().toString(););
thanks.
using it as follows:
<script language="JavaScript">
function getQueryString() {
var assoc = new Array();
var queryString = unescape(location.search.substring(1));
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
assoc[key[0]] = key[1];
}
return assoc;
}
</script>
<script language="JavaScript">
alert('?h='+getQueryString()["search"];);
//localSearchHighlight('?h='+getQueryString()["search"]);
);
</script>
Your code has syntax errors, in the second <script> block. It should read:
alert('?h='+getQueryString()["search"]);
There was a ; inside the function call parens.
You had an additional line with ); after your comment.
Other than that, it seems to work like you want it too.
Take a look in your browser's error console; alert('hello'+getsomestring();) is a syntax error due to the semicolon. Semicolons separate lines and shouldn't appear in expressions. Remove it, and the expressions will work (as you have it typed at first: alert('hello'+getsomestring());).
There are no associative arrays in JavaScript. Only objects map keys to values.
Replace var assoc = new Array(); with var assoc = new Object(); or the shorthand var assoc = {}; then it works.
Also there's an superflous ; in your alert:
alert('?h='+getQueryString()["search"];);
^ --------- SyntaxError: Unexpected token ;

How can I print javascript objects?

I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...

Categories

Resources