We have a script run early on our page that feeds values to a third party.
foo.bar.myPage({
"myId": "12345",
"myName": "My name is Joe",
});
I want to create a new variable using one of those values and use it for something else. I can't figure out how to grab the value from above. I do not have access to the code above - need to do this using javascript or jquery via a CMS. Help?
var valueFromMyId = $(myId);
alert (valueFromMyId);
Obviously I want "12345" to fire in my alert.
I Tried something like this:
foo = {
"bar":{
"myPage":function(param){
console.log("inside"+param);
}
}};
foo.bar.myPage(123); //print inside 123
Now Try this to override, if you can access foo.bar.
var backup = foo.bar.myPage
foo.bar.myPage = function(param){
console.log("Using params outside the actual function "+ param);
//calling the actual function which was getting called initially
backup(param);
}
now every foo.bar.myPage call will go through your define method, that way you can access param before the actual function gets it.
This might not be the best way to do it. But will work if you have access to foo.bar object. Test and let me know if this helps.
Related
I am trying to get some parameters form the URL and pass them on to another function.
The function for getting the parameters is like that:
function getUrlVars(callback) {
var urlVars = {};
var urlparts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
urlVars[key] = value;
});
callback(urlVars);
}
It gets the parameters just fine. The function that urlVars should be passed to, looks like this:
document.addEventListener('done', function() {
var projSelect = document.getElementById('projectSelection');
projSelect.value = urlVars[0];
});
});
};
I am calling both functions like so:
window.onload=function(){
getUrlVars(selectBox(urlVars));}
So all I am trying to do, is set the value of a selectbox according to a parameter in the URL. But I get an error, telling me that "urlVars" ist not defined.
And quite frankly, I am at my wits end. Can anybody tell me what I did wrong?
The problem you are having, is that when you are defining the method for window.onload you are passing a parameter that is not defined anywhere in your script.
Furthermore, it seems like you want to pass a callback method to urlVars, but you are passing a parameter? It is hard to tell by the code that you have provided.
Why not get the parameters you want from your select box and then send them to the desired method?
Ok hopefully this come across correctly. I am building a universal javascript function that will build a menu and then also build the functions that each menu item would call. To do this, I need to pass a list of the commands to be called for each option.
So for example:
var thecall = 'alert("hi, this works");';
function myfunction(thecall)
{
//In here I want to excute whatever commands is listed in variable thecall
.....
}
I'm sure doing it this way is completely stupid, but I don't know how else to do this.
Basically, I need my function to perform other functions on a variable basis.
Thanks!!
I made it a bit fancier to show you how you can use it.
var thecall = function(name){alert("hi " + name + ", this works");};
function myFunction(function_ref)
{
function_ref('Mark');
}
myFunction(thecall);
You can execute arbitrary strings of JavaScript using eval(), but that is not the best solution for you here (it's almost never the best solution).
Functions in JavaScript are themselves objects which means you can store multiple references to the same function in multiple variables, or pass function references as parameters, etc. So:
var thecall = function() {
alert("hi, this works");
};
function myfunction(someFunc) {
someFunc(); // call the function that was passed
}
myfunction(thecall); // pass reference to thecall
Note that when passing the reference to the thecall function there are no parentheses, i.e., you say thecall not thecall(): if you said myfunction(thecall()) that would immediately call thecall and pass whatever it returned to myfunction. Without the parentheses it passes a reference to thecall that can then be executed from within myfunction.
In your case where you are talking about a list of menu items where each item should call a particular function you can do something like this:
var menuItems = [];
function addMenuItem(menuText, menuFunction) {
menuItems.push({ "menuText" : menuText, "menuFunction" : menuFunction });
}
function test1() {
// do something
}
addMenuItem("Test 1", test1);
addMenuItem("Test 2", function() { alert("Menu 2"); });
// and to actually call the function associated with a menu item:
menuItems[1].menuFunction();
Notice the second menu item I'm adding has an anonymous function defined right at the point where it is passed as a parameter to addMenuItem().
(Obviously this is an oversimplified example, but I hope you can see how it would work for your real requirement.)
I think your looking for the eval function.
var code= 'alert("hi, this works");';
eval(code);
I'm making an AJAX call which returns XML data, and this is my 'success:' function (callback):
success: function (data) {
var $rowArray = $(data).find("[nodeName=z:row]");
$rowArray.each(function(index) { // for each date put it into calMap.
calMap[$(this)[index].title] = $(this).attr("ows_Title");
calMap[$(this)[index].date] = $(this).attr("ows_EventDate");
});
}
calMap is a global javascript object declared outside of the function.
var calMap = {};
What I want to do is create a function where I can pass in a title, have it search calMap for that title, and if found, the specific object is returned and I'll be able to access the date property for that object.
Problem is, I can't seem to access the data I insert into the calMap object. For starters, I just want to print the map. Tried eval'ing it, tried alerting calMap[0], tried alerting calMap[0].title, but nothing. Can someone help me with this? Thanks!
Update:
I want to do something like this:
var data = getData("myTitle");
function getData(title) {
// if title is in calMap, something like this?
var result = (calMap[title]));
return result; // returns an object or NOTHING
}
then i'll check if date is defined or not, and if it is, i'll access its properties (ie. data.date. That make sense?
ANSWER:
I ended up using an array. STILL think I should be able to use the object MAP, but needed to get my project done.
Here's the final code for the code that accesses the array items:
function hasCalDate(code)
{
var matched = "";
for (var f=0;f<calMap.length;f++){
var re = new RegExp(code);
if (re.test(calMap[f].title))
{
matched = calMap[f].title+','+calMap[f].date;
}
}
return matched;
};
Thanks everyone.
You need to initialize calMap as an array (i.e. square brackets, not curly ones):
var calMap = [];
Then, inside your each function, I'm guessing you want something more like
calMap.push({
title: $(this).attr("ows_Title"),
date: $(this).attr("ows_EventDate")
});
Your problem is that the success function is only run when your AJAX request completes. If you want to access calMap safely, you need to do so inside your callback.
I want to do something that in a classical object oriented language like Java, C# etc. is very easy to do. I simply want to access a property of an instantiated object. The object is globally scoped in the browser's window object, and provided by the twitter #anywhere API.
For my code examples, assume you have already logged the user in.
If I were using java for instance, I would say (assuming all fields were public:
twttr = new twtter();
String screenName = twtter.currentUser.data('screen_name');
For some reason, this is way hard in Javascript. I've gotten a workaround working where inside the anonymous method that the twitter anywhere API is using, I set the value I want to a DOM element, and fish it out later. This is ugly though. I just want to access it directly.
Here's what I have so far, which doesn't even pass syntax checks in eclipse:
function AnywhereFacade()
{
var twitterReference;
window.twttr.anywhere
(
return function(T)
{
twitterReference = T;
};
)
getValue(propertyToGet)
{
return twitterReference.currentUser.data(propertyToGet);
}
};
var anywhereFacade = AnywhereFacade();
var screen_name = anywhereFacade.getValue("screen_name");
alert("screen name is: " + propertyGetter);
Please help! Why is Javascript so hard to use anyway? What I'm trying to do is use a closure I think.
Thanks!
I have done something similar in my app since I am using the Facebook JavaScript SDK and Twitter SDK and want to provide a consistent interface to access both. So I namespace the variables under App. For twitter anywhere, this is how the variable is captured.
window.App = {};
twttr.anywhere(function(T) {
App.Twitter = {
getValue: function(property) {
return T.currentUser.data(property);
},
getPublicTimeline: function() {
return T.Status.publicTimelime();
}
};
});
We are calling the anywhere function and passing it a callback function. The callback function is needed because the anywhere library might not be loaded at this point. By passing the entire function, we are saying that this function should be executed whenever the anywhere library is loaded.
Now when the library does load, this function will execute, define the App.Twitter property which contains a getValue function. The anywhere or T object is captured in the closure.
If you now call,
App.Twitter.getValue("screen_name");
the actually anywhere object (T), will be used to get the screen_name property.
this is all I needed to do.
document.getElementById('messagePanel').innerHTML = "loading...";
window.twttr.anywhere(function(T)
{
document.getElementById('messagePanel').innerHTML = "screen_name: " + T.currentUser.data('screen_name');
});
this made me realize my issue was just that I had to use a callback for when twitter returned from the async call. that helped me solve my initial problem of how to wrap it for gwt.
I plan on using JSONP to call an external web service to get around the fact that I don't want to create a global function that could potentially conflict with the calling page. I thought that creating a random function name and passing it up would work. Something like this:
<script src="www.foo.com/b?cb=d357534">
where cb is the callback function name, the server would return
d357534({my json data});
What I want to know is how to create the random function name, I'm sure I could use eval but is this the best way to go about it?
Essentially, what I am trying to do is this:
var d + Math.floor(Math.random()*1000001) = function(){...
This should do what you want. You need to save the function name somewhere so that you can pass it to the server, but you can do that inside of a local scope to avoid polluting your global namespace.
var functionName = 'd' + Math.floor(Math.random()*1000001);
window[functionName] = function() { ... }
To make a randomly-named global variable you could do this:
window['randomvar' + Math.floor(Math.random()*1000001)] = function() { ... };
now of course you've got the problem of remembering the random name somewhere. You could make up a random name for that variable too. Then you'd have to remember the name of that variable, so that you could look at its value and then know how to find your function. After a while, things are going to start getting weird.
Why don't just use a counter and increment it each time you need a new function:
var name = "callback" + window.COUNTER++;
window[name] = function() { ... };
If you want to avoid littering the global namespace with too many references you could (and should) attach the counter and callbacks to a single global object:
var JSONP = window.JSONP;
var name = "callback" + JSONP.COUNTER++;
JSONP[name] = function() { ... };
In this case you could call the method like this:
JSONP.callback_12(json);
Of coarse you have to initialize the JSONPobject and the COUNTER variable first.