我重寫從YUI 2我的應用程序YUI 3將數據傳遞給YUI 3 JavaScript應用
有時候,我需要在我的JavaScript環境從數據庫中一些數據的工作。杉杉選項是分配在JavaScript中一些全局變量,但是全局變量是不好的,所以我也按照YUI 2:
app.js
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>';
?>
正如你可以看到我使用「公共方法」 YAHOO.MyApp.initUserInfo和YAHOO.MyApp.initCurrencyRates將數據傳遞到JavaScript代碼。
現在我該怎麼使用YUI 3重寫一遍:
app.js
YUI().use('node', 'event', function(Y) {
var currencyRates;
var userInfo;
/*
here a lot of code with event listeners and dom manipulations which uses currencyRates and userInfo variables
*/
})
PHP
<?php
$currencyRates = array('EUR' : 1.3245, 'GBP': 1.4322, 'RUB': 0.02334); //actually it comes from database
print '<script>???</script>';
?>
如何提供 「公共方法」在我的YUI 3 JavaScript代碼中? 或什麼是另一種解決方案通過內部的JavaScript應用程序代碼aviding全局變量的數據?
在最後幾天,我對YUI 3瞭解很多,並發現選項2)(火災事件)將是有用的!但是你提到如果發現條件,它會失敗。使用('...',...)是否可以將火焰放入另一個YUI()中? – Petr 2012-02-06 19:11:55
最好將頁面上的YUI實例數量保持在最小。使用模塊而不是再次執行'YUI()。use ...'。 – Luke 2012-02-08 01:00:55