玩!框架:在单独的 JavaScript 文件中使用 URL 的最佳实践? [英] Play! Framework: Best practice to use URLs in separate JavaScript files?

查看:22
本文介绍了玩!框架:在单独的 JavaScript 文件中使用 URL 的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在重组 Play!有很多JS的项目HTML 模板文件中的代码.此代码应移至外部JS 文件以获得更好的可读性和更快的页面加载时间.然而,当我在 public 文件夹中创建一个 JS 文件时,所有的@{Controller.method} 链接替换不再有效.我曾是考虑从 HTML 调用一些初始化函数仅提供所需 URL 的模板,例如

I am currently reorganizing a Play! project where there is a lot of JS code in the HTML template files. This code should be moved to external JS files for better readability and faster page loading times. However, when I just create a JS file in the public folder, all the @{Controller.method} link replacements are no longer working. I was thinking about calling some initialization function from the HTML templates which just supplies the required URLs like

initialize({ "Application.doThis" : "@{Application.doThis}"})

然而,这对于任何 URL 都变得非常麻烦且容易出错这是添加的.另一件事是,I18N 也不再有效.所以对于这些场景的最佳实践是什么,在那里你有你的单独文件中的 JS 代码但仍想使用 URL 生成和JS 中的 I18N?

however this is becoming very cumbersome and error-prone with any URL that is added. Another thing is, that the I18N also no longer works. So what is the best practice for scenarios like these, where you have your JS code in a separate file but still want to use URL generation and I18N in your JS?

推荐答案

在主模板中,生成一个 'Javascript router',类似于:

In the main template, generate a 'Javascript router', something like:

<script>
    var routes = {
        doThis: #{jsAction @Application.doThis(user, ':param1', ':param2') /},
        doThat: #{jsAction @doThat() /}
    } 
</script>

然后在任何静态"javascript 文件中,使用此路由器:

And then in any 'static' javascript file, use this router:

$.get(routes.doThis({param1: x, param2: 'yop'}))

这篇关于玩!框架:在单独的 JavaScript 文件中使用 URL 的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆