如何以正确的方式在Rails中做history.js?

Ben*_*n M 5 ruby-on-rails history.js

嗨,大家好,

它现在是我第四次尝试在Rails应用程序中实现history.js.我有一种方法运行得很好,但代码是如此丑陋.今天我再次查看代码并思考:如何让这更好,更容易,更干?!

到目前为止我做了什么(并且工作得很好,不完美):

  • 设置remote: true为我的链接
  • jquery-ujs抓住了 js.erb

我的HTML看起来像:

<body>
  <div id="content">
    some content with buttons, etc.
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

js.erb包含:

History.pushState(
  {
    func: '$(\'#content\').html(data);',
    data: '<%= j(render template: "news/index", formats: [:html]) %>'
  },
  'test title',
  '<%= request.url %>'
);
Run Code Online (Sandbox Code Playgroud)

然后history.js接受函数并为其提供数据.所以它用content新生成的代码替换-div.它还会更新URL.这段代码我必须放在每个(!)js.erb文件中.

我最后想让它变得不那么难看的是:

  • 设置remote: true为我的链接
  • 单击链接时,会获取一些js.erb替换content-div的链接
  • 所有链接data-remote="true"都将获得ajax:success-handler
  • ajax:success新URL上被推送到history.js

但是内部仍然存在一个问题.然后我有JavaScript代码:

$(document).on('ajax:success', 'a[data-remote="true"]', function() { ... });
Run Code Online (Sandbox Code Playgroud)

问题是:ajax:success如果我替换div了链接(应触发事件)所在的-tag,则永远不会触发.

也许有人可以解决我的问题......

或者,还有更好的方法?

jog*_*aco 2

我只使用jquery-ujs和pushState,popState。

在这里查看我的回答:

/sf/answers/1927306251/