2012-02-02 40 views
2

我重寫從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全局變量的數據?

回答

0

您有幾種選擇:

1)代碼內YUI沙箱可以訪問沙箱外部變量,因此只存儲數據的地方,並引用其沙箱裏面的代碼。這隻適用於數據,不能調用方法。

注意,這不涉及任何形式的通知,所以它是由在YUI沙箱知道什麼時候數據可用的代碼。

// PHP 
print '<script>YUI.namespace('Env.MyApp.data').currencyRates = ' . json_encode($currencyRates) . ';</script>'; 

// YUI (inside the YUI().use() callback) 
var currencyData = YUI.Env.MyApp.data.currencyData; 

從技術上講,使用這種方法,您可以將數據放在全球任何地方,並且它可以工作。

2)使用共享的全局事件目標Y.Global(又名YUI.Env.globalEvents)播出由您的沙箱內事件訂閱接收的消息。

這可以讓你有一個函數上述追加數據的頁面,但如果PHP產生的貨幣數據,同時建立了頁面的標記,因爲這是一個失敗的競爭條件不起作用。

// PHP 
print "<script>YUI.Env.globalEvents.fire('myapp:data', { currencyRates: " . json_encode($currencyRates) . " });</script>"; 

// YUI 
Y.Global.on('myapp:data', function (e) { 
    // the data is in e.currencyRates 
}); 

3)如果數據是指靜態交付和YUI()調用之前頁面裝配在PHP中加入它,只是它包裝到一個模塊中,並使用()它。

// PHP 
print "<script>YUI.add('myapp-currency-rates', function (Y) { Y.namespace('MyApp.data').currencyRates = " . json_encode($currencyRates) . "; });</script>"; 

// YUI 
YUI().use('myapp-currency-rates', … function (Y) { 
    // the data is in Y.MyApp.data.currencyRates 
}); 

而且根據數據傳輸的時間以及頁面和傳遞數據的php之間的關係,您還有其他選擇。在本週期間,在freenode上停止#yui,會有很多人幫你找出最佳的解決方案。

+0

在最後幾天,我對YUI 3瞭解很多,並發現選項2)(火災事件)將是有用的!但是你提到如果發現條件,它會失敗。使用('...',...)是否可以將火焰放入另一個YUI()中? – Petr 2012-02-06 19:11:55

+0

最好將頁面上的YUI實例數量保持在最小。使用模塊而不是再次執行'YUI()。use ...'。 – Luke 2012-02-08 01:00:55