document.ready 未由 pjax 触发
我正在为我正在开发的应用程序尝试 pjax,但我有点碰壁了。
也许我以错误的方式处理这个问题,让我解释一下。
在应用程序中,我的顶部有一个主菜单,其中包含不同的部分。此菜单中的每个链接都启用了 pjax,这意味着只有应用程序的主体会发生更改。
通常,当您单击没有 pjax 的链接时,将触发 document.ready 方法。我用它来将事件绑定到按钮,如下例所示。
这是我的 users.js.coffee 文件
loaded = false;
$ ->
$("#btn_new_user").bind "click", (event) ->
if not loaded
@path = $('#btn_new_user').attr("path")
$("#new-users-container").load(@path)
loaded = true
$("#new-users-container").slideToggle()
正如您在本例中看到的,当“users”页面完成加载时,它将绑定一个带有事件的按钮,该事件会将表单加载到 div 中并为其设置动画以显示它。
但是,当我从管理的不同部分开始并单击“用户”链接以显示此按钮时,该事件未绑定。当我重新加载“用户”部分中的页面时, document.ready 会触发并且按钮工作正常。
是否有更好的技术将事件绑定到按钮,或者是否有某种方法在 pjax 上触发 document.ready?
谢谢。
I'm trying out pjax for an app I'm developing but I've kinda hit a wall.
Maybe I'm going about this the wrong way, let me explain.
In the app, I have a main menu on top, with the different sections. Each of the links in this menu are pjax enabled, meaning that only the body of the application will change.
Normally, When you click a link with no pjax, the document.ready method will be triggered. I use this to bind events to buttons like the following example.
here is my users.js.coffee file
loaded = false;
$ ->
$("#btn_new_user").bind "click", (event) ->
if not loaded
@path = $('#btn_new_user').attr("path")
$("#new-users-container").load(@path)
loaded = true
$("#new-users-container").slideToggle()
As you can see in this example, when the "users" page finishes loading, it will bind a button with an event that will load a form into a div and animate it to show it.
However, when I start in a different section of the admin and click on the Users link to show this button, the event is not binded. When I reload the page in the Users section, the document.ready triggers and the button works fine.
Is there a better technique to bind the events to buttons or is there some way to trigger document.ready on pjax?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是我目前正在做的事情。
对于其他初始化,以这种方式实现(在原始 Javascript 中)
Here's how I'm currently doing this.
For other initialization, implement it this way (in raw Javascript)
好吧,昨天学到了一些东西。
首先,像这样声明 CoffeeScript 将使代码仅可用于该文件,而无法在其他任何地方访问。
解决这个问题的常见方法是,例如
,在其他地方你
无论如何都可以这样做,这只是问题的一部分,真正的解决方案是使用委托 http://api.jquery.com/delegate/ 方法,该方法允许您在元素不存在的情况下绑定元素。
Ok, learned a couple of things yesterday.
First, declaring coffeescript like that will make the code available only to that file and not accessible anyplace else.
The common way around this is, for example
then in some other place you can do
anyway, that was just part of the problem, the real solution was using the delegate http://api.jquery.com/delegate/ method, which allows you to bind elements without them being there.
这将完美地工作:
您所需要做的就是在完成 pjax 请求后包含您的脚本。
希望有帮助..!!
This will work perfect:
All you need to do is include your script after completion of pjax request.
Hope it helps..!!