大家好,
现在我第四次尝试在Rails应用中实现history.js。我有一种方法运行得很好,但代码太难看了。今天我又看了一遍代码并思考:我怎样才能让这个更好,更容易,更干??如何以正确的方式在rails中执行history.js?
我迄今所做的(和工作相当好,不完美):
- 设置
remote: true
到我的链接 - jQuery的UJS取的
js.erb
我的HTML看起来像:
<body>
<div id="content">
some content with buttons, etc.
</div>
</body>
该js.erb
包含:
History.pushState(
{
func: '$(\'#content\').html(data);',
data: '<%= j(render template: "news/index", formats: [:html]) %>'
},
'test title',
'<%= request.url %>'
);
然后history.js需要的功能,并赋予它的数据。所以它用新生成的代码替换content
-div。并且它也更新了URL。这个代码我必须放在每个(!)js.erb
文件中。
我最后的想法,使其少一点丑陋分别为:
- 设置
remote: true
到我的链接 - 当一个链接被点击它提取一些
js.erb
它取代了content
-div - 所有链接与
data-remote="true"
将得到ajax:success
处理程序 - 在
ajax:success
新的URL被推送到history.js
但内部仍然存在一个问题。然后,我有JavaScript代码:
$(document).on('ajax:success', 'a[data-remote="true"]', function() { ... });
的问题是:ajax:success
永远不会触发如果我更换div
-tag其中链路(即应触发事件)是
也许有人可以解决我的问题...
你见过jquery.pjax? – 2012-04-10 21:33:54
我已经看了很多次histoy.js页面,但从未尝试过尝试实际尝试它。我很想看到这个问题以一种明确的方式回答。 – Ashitaka 2012-04-10 21:48:30
PJAX仅适用于HTML5。 HTML4浏览器只是得到正常的链接...随着history.js我们也得到AJAX的HTML4浏览器 – 2012-04-11 05:07:48