1

问题可能很明显,但我仍然找不到合适的解决方案。

让我们假设有一个控制器只有一种方法:

class MyController extends Controller {
    public static Result sum(int op1, int op2) {
        return ok(op1 + op2);
    }
}

Routes 文件也很简单:

GET /sum    controllers.MyController.sum(op1: Integer, op2: Integer)

好吧,现在我可以从模板调用:

@controllers.routes.MyController.sum(1, 2)

这将被翻译成

localhost:9000/sum?op1=1&op2=2

,或直接将此网址粘贴到浏览器中。这工作得很好。

但是当我决定使用 ajax 来做这件事时,一切都变糟了。我不是 js-guru,所以我使用 jQuery 编写小的(我认为很糟糕:)对象,它将 onClick 处理程序添加到按钮。这里是:

entityController.setSumURL = function(sumURL) {
    this.sumURL = sumURL;
}

entityController.bindSumButton = function(buttonId, op1, op2) {
    $.get(entityController.sumURL, {op1: op1, op2, op2}, function(){
        alert("Done!");
    });
}

其中 entityController.sumURL 应该是 /sum 方法的 url。通常当我渲染页面视图时,我会写这样的东西:

@()
....
entityController.setSumURL("@controllers.routes.MyController.sum()")
....

但我不能这样做,因为 sum 方法具有强制参数,并且无法获取地址,因为绑定的 url 可以依赖传递给路由中定义的函数的参数。

所以问题是如何只从不带参数的 url 获取路径,或者如何重新组织整个过程以避免这种情况?

我的解决方案是从出现在路由中的函数中删除参数并直接从请求中查询它们,但是我的项目正在增长,有时很难理解哪些参数传递给方法。

4

1 回答 1

2

Check out the zen tasks sample application.

In particular:

You may want to compile this app and look at the output javascript rather than the coffeescript if you're not familiar with coffeescript.

Also, if you're reloading parts of the page using ajax, you may want to bind your jQuery using

$('.somePermanentContainer').on('click', 'selectorForClickable', function()...) 

otherwise you'll find it's no longer bound when that part of the DOM is reloaded.

于 2012-08-14T10:44:57.963 回答