I got the following code from here, while searching for some way to access PHP variables from a YUI2 JavaScript function in a separate .js file.
Looking at the JavaScript, the first statement creates the namespace, the second statement starts the definition of a function (named as YAHOO.MyApp). Then var currencyRates; and var userInfo; create two variables.
Then what is the next
return {...}construct?Then inside that,
function(newRates) { currencyRates = newRates; }looks like a function (especially because PHP probably calls it and passes to it the array$currency rates? But overall what isinitCurrencyRates: function(newRates) { currencyRates = newRates; }?What is
:there (just like=is for assignment)?Then what about the
();in the end? What is thesomething=function(){...}();construct?
Can somebody explain the control flow? What is executed first and then what and then what?
JavaScript:
YAHOO.namespace('MyApp');
YAHOO.MyApp = function() {
var currencyRates;
var userInfo;
/*
here a lot of code with event listeners and dom manipulations which uses currencyRates and userInfo variables
*/
return {
initCurrencyRates: function(newRates) { currencyRates = newRates; },
initUserInfo: function(newUserInfo) { userInfo = newUserInfo; },
}
}();
PHP:
<?php
$currencyRates = array('EUR' : 1.3245, 'GBP': 1.4322, 'RUB': 0.02334); //actually it comes from database
print '<script>YAHOO.MyApp.initCurrencyRates(' . json_encode($currencyRates) . ')</script>';
$userInfo = array('Name' => 'Jhon', 'ID' => 10); //actually it comes from database
print '<script>YAHOO.MyApp.initUserInfo(' . json_encode($userInfo) . ')</script>';
?>
You are looking at Javascript object literals. They are a bit similar to PHP's hash literals. This Javascript code
Is a bit similar to this PHP code: