这是我遇到的问题。我有这些过滤器,它们每个都有自己的url,它们是由辅助方法filter_url(filter_name)
生成的。我想在url更改时异步更新这些过滤器URL(AJAX)(这也是异步发生并使用HTML5的History API推送)。但是,我无法弄清楚如何更新这些过滤器URL,因为我需要知道我正在生成url的过滤器的名称(在data-name
DOM属性中是客户端)但是{{1服务器端。 一个肯定的解决方案是移动filter_url
逻辑客户端,但是我必须维护客户端和服务器端逻辑来处理根本不是DRY的过滤器URL 。所以说,我正在尝试做什么或者我是以错误的方式接近它?谢谢你一千块蜂蜜燕麦!
也许SO应该为源代码添加一些gist类型的功能,您可以通过文件将其拆分。也许这可能具有更好的可读性:https://gist.github.com/4c91435aefde9ad5846f。但是我也会在这里粘贴我的代码,以防我的要点到期。
filter_url
_filters.html.haml
%ul#filters
- @filters.each do |filter|
%li
%a{:"data-name" => filter.name, :href => filter_url(@url_filters.add_to_url(filter.name))}
filters.js.coffee
$('#filters li a').live 'click', ->
history.pushState(null, "", @href) # This changes the url (not using hash bangs)
$.getScript(@href) # This will call index.js.coffee
filters_controller.rb
class FiltersController < ApplicationController
def index
@url_filters = URLFilters.parse(request.fullpath)
end
end
index.html.haml
= javascript_include_tag :filters
= render "filters"
index.js.coffee
答案 0 :(得分:0)
好吧,所以我觉得我找到了一个稍微优雅的解决方案。
我将 index.js.coffee
更改为
# Render the partial and get a DOM fragme
filters = $('<%= escape_javascript(render("filters")) %>')
# Replace all filter urls from the ones in the DOM fragment
$('a.filter-url', filters).each ->
$('#' + @id).attr('href', @href) # Replace the href by selecting the id which is unique
然后还将部分 _filters.js.coffee
更改为
%ul#filters
- @filters.each do |filter|
%li
%a{:id => "#{filter.name}-#{filter.value}", :href => filter_url(@url_filters.add_to_url(filter.name))}
所以我现在正在做的是将过滤器部分渲染并从中创建一个DOM片段,并使用jQuery选择该DOM片段中的所有过滤器URL。然后,我将DOM片段URL替换为当前视图中的URL片段。似乎运作良好,但我对任何其他想法持开放态度!希望这将有助于遇到类似情况的其他人。