I realize this is javascript 101 and there are many questions along these lines on SO but I am extremely rusty on JS and can't seem to get this to work.
I am trying to change a parameter in some javascript B that calls a widget using another script A. It is important that A set the value in B before B is called so that B uses the desire value.
Here is the code I have right now:
A.
<script type="text/javascript">
function getName() {
return "Raoul Walsh";
}
</script>
B.
<script type="text/javascript">
new MyView.widget(
{
"name": "getName()",
"locale": "en"
}
);
</script>
The widget is not recognizing the value I want: 'Raoul Walsh' but instead recognizing the value 'getName()'. In other words it does not realize, I'm trying to call a function.
BTW, I also tried setting the value using the DOM unsuccessfully.
How can I set the value for the widget script before it executes so that it executes using my desired value.
Thanks in advance for any suggestions
1 Answer 1
You don't need the quotes, simply call getName()
<script type="text/javascript">
function getName() {
return "Raoul Walsh";
}
</script>
<script type="text/javascript">
new MyView.widget({
"name": getName(),
"locale": "en"
});
</script>
In case javascript doesn't recognize the function, there may be some scoping issue going on that are hard to debug without having the full page.
In that case, you can fix the problem by attacching the function to the window object
<script type="text/javascript">
window.getName = function() {
return "Raoul Walsh";
}
</script>
<script type="text/javascript">
new MyView.widget({
"name": window.getName(),
"locale": "en"
});
</script>