rails4 新增了turbolinks插件,可以在项目的gemfile中看到
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
项目的manifest文件(一般是application.js)中
//= require turbolinks
这个gem官方文档里有这么一句话
With Turbolinks pages will change without a full reload, so you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code. Instead Turbolinks fires events on document to provide hooks into the lifecycle of the page.
page:before-change
a Turbolinks-enabled link has been clicked (see below for more details)page:fetch
starting to fetch a new target pagepage:receive
the page has been fetched from the server, but not yet parsedpage:change
the page has been parsed and changed to the new version and on DOMContentLoadedpage:update
is triggered whenever page:change is PLUS on jQuery's ajaxSucess, if jQuery is available (otherwise you can manually trigger it when calling XMLHttpRequest in your own code)page:load
is fired at the end of the loading process.
当然也可以不用这个插件,方法是,把gemfile中的gem turbolinks注释掉,还有就是把去掉manifest文件中的
//= require turbolinks
就可以和往常一样使用了。
不过在有这个插件的情况下,也可以在元素里加上属性:data-no-turbolink,这样的话这个元素就不会用到该插件了,正常使用。
例如页面这样一个link
<a href="#" data-background-color = "#990000" data-no-turbolink >Paint it red</a>
对应的js.coffee这样写
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
$ ->
$("a[data-background-color]").click ->
backgroundColor = $(this).data("background-color")
textColor = $(this).data("text-color")
paintIt(this, backgroundColor, textColor)
点击该link,会使自身背景变为深红色,
当去掉 data-no-turbolink 这个属性时,点击该link是没有反应的。
我也尝试了用turbolinks的事件来响应该点击事件,我这样做link
<a href="#" data-background-color = "#990000">Paint it red</a>
对应的js.coffee这样写
paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
$ .on "page:change",->
$("a[data-background-color]").click ->
backgroundColor = $(this).data("background-color")
textColor = $(this).data("text-color")
paintIt(this, backgroundColor, textColor)
虽然我用了page:change,但是效果却不是我想要的,点击link后,会变成深红色,不过马上又变回去了,还是对这个理解不深,不会使用的原因。
刚把利马斯!!