method plugin doesn't work within Function Constructor - javascript

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.

Related

Angularjs function meaning

I am a beginner in programming. I would like to understand what the beginning of this angular function is doing line by line ?
function UserProfileService($http, ApiConfigService) {
var profileUrl = ApiConfigService.getEndpoints().user_service +
'/v2/users/profile';
var oauthUrl = ApiConfigService.getEndpoints().oauth_service +
'/v2/oauth';
Thanks!
It is creating two different string variables. The base url comes from the ApiConfigService and rest is concatenated there to the baseurl.
We could assume the following:
ApiConfigService.getEndpoints().user_service = 'http://example.com/user-service'
ApiConfigService.getEndpoints().oauth_service = 'http://example.com/oauth-service'
then the variables here would get the following values:
profileUrl = 'http://example.com/user-service/v2/users/profile'
oauthUrl = 'http://example.com/oauth-service/v2/oauth'

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

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.

JS How to include a variable in a path?

The following variable contains a string that is a path to an image.
iconBlue.image = 'http://www.site.com/icon1.jpg';
How can include a variable in this path? Let me explain more detailed. Lets say there are many icons in a folder icon1.jpg icon2.jpg etc. I have a variable named iconspec that depending on its value (1 or 2 or 3 etc) points to the icon I must use.
How can i include variable iconspec in the path?
iconBlue.image='http://www.site.com/icon"iconspec".jpg
Something like this i guess but with correct syntax.
You just need to put it like a simple string with variable.
In your case, you should do this:
iconBlue.image = 'http://www.site.com/icon'+iconspec+'.jpg';
The + operator is like the . in PHP, it merge string.
iconBlue.image='http://www.site.com/icon'+iconspec+'.jpg';
To take a little different route, you could encapsulate the concatenation in a function and make it a bit more reusable:
var icon = function(){
this.path = '';
this.imageName = '';
this.imagePath = function() { return this.path + '/' + this.imageName };
};
var iconBlue = new icon(),
iconRed = new icon();
iconBlue.path = "c:\\stuff";
iconBlue.imageName = "icon1.jpg";
iconRed.path="c:\\morestuff";
iconRed.imageName = "icon2.jpg";
alert(iconBlue.imagePath());
alert(iconRed.imagePath());
The simplest solution is to use the + to concatenate the variable to the string:
var name = 'sachleen';
var result = 'my name is ' + name;
Output: my name is sachleen
There are a couple of more powerful options available as well.
JavaScript sprintf() is a sprintf implementation for JS.
string.format in JS

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 );

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