2013-05-10 68 views
1

我正在構建一個模塊化JavaScript應用程序(RequireJS/Backbone),並且正在尋找一些關於將服務器端URL傳播到JS應用程序以用於客戶端模板的最佳實踐的建議,API請求等。在Javascript應用程序中維護服務器端API url

將其注入到啓動Javascript應用程序的基本模板中? 專門爲此目的的API請求?

很想聽聽其他人使用的解決方案。謝謝!

回答

0

您可以在body中呈現<script>標記,定義模塊並以任何您喜歡的方式放置您的URL。
之後,你可以在你的模塊(.js文件)中要求它。

HTML(例如,您的應用程序佈局):

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Inline RequireJS define</title> 
    </head> 
    <body> 
     <h1 id="foo-holder"></h1> 
     <a id="sign-up-link" href="#"></a> 
     <script> 
      // This is rendered by your server-side application: 
      define('data/config', function(require, exports, module) { 
       exports.Url = { 
        HOME: 'https://mysite.com', 
        SIGN_IN: 'https://mysite.com/sign-in', 
        SIGN_UP: 'https://mysite.com/sign-up', 
        LOG_OUT: 'https://mysite.com/log-out' 
       }; 

       exports.foo = 'bar'; 
      }); 
     </script> 
    </body> 
</html> 

的JavaScript(在你的模塊某處):

// This is somewhere in your JavaScript module 
require(['data/config'], function(Config) { 
    $('#foo-holder').text(Config.foo); 
    $('#sign-up-link') 
     .text(Config.Url.SIGN_UP) 
     .attr('href', Config.Url.SIGN_UP); 
}); 

DEMO


另一個TR ick可以通過某種屬性綁定來完成。

在您的佈局:

<a data-url="HOME" href="#">Home</a> 
<a data-url="SIGN_IN" href="#">Sign In</a> 
<a data-url="SIGN_UP" href="#">Sign Up</a> 
<a data-url="LOG_OUT" href="#">Log Out</a> 
<script> 
    // This is rendered by your server-side application: 
    define('data/config', function(require, exports, module) { 
     exports.Url = { 
      HOME: 'https://mysite.com', 
      SIGN_IN: 'https://mysite.com/sign-in', 
      SIGN_UP: 'https://mysite.com/sign-up', 
      LOG_OUT: 'https://mysite.com/log-out' 
     }; 

     exports.foo = 'bar'; 
    }); 
</script> 

在你的JavaScript文件:

// This is somewhere in your JavaScript module 
require(['data/config'], function(Config) { 
    $('a[data-url]').each(function() { 
     var $a, 
      urlConstant, 
      url; 
     $a = $(this); 
     urlConstant = $a.data('url'); 
     url = Config.Url[urlConstant]; 
     if(url) { 
      $a.attr('href', url); 
     } 
    }); 
}); 

DEMO

+1

大,這是非常接近對我將是方向使用。稍後,我將把URL模塊的內容傳遞到我使用的客戶端模板庫中,而不是使用jQuery來更改URL。所以我會在我的模板中使用{{Config.url.SIGN_IN}}或其他類似的URL。 – 2013-05-11 20:37:32

+0

當然,您可以將配置傳遞給模板並在其中使用其常量。 – 2013-05-11 22:15:56

相關問題