Skip to content

Commit

Permalink
Merge pull request #262 from Hexawise/master
Browse files Browse the repository at this point in the history
Update event listener setup
  • Loading branch information
michelson authored Aug 18, 2021
2 parents 412a2c1 + 3736dbd commit fd5c4f7
Showing 1 changed file with 26 additions and 39 deletions.
65 changes: 26 additions & 39 deletions lib/lazy_high_charts/layout_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,45 +92,20 @@ def options_collection_as_string object
end

def encapsulate_js(core_js)
if request_is_xhr?
js_output = "#{js_start} #{core_js} #{js_end}"
# Turbolinks.version < 5
elsif defined?(Turbolinks) && request_is_referrer?
js_output =<<-EOJS
#{js_start}
var f = function(){
document.removeEventListener('page:load', f, true);
#{core_js}
};
document.addEventListener('page:load', f, true);
#{js_end}
EOJS
# Turbolinks >= 5
elsif defined?(Turbolinks) && request_turbolinks_5_tureferrer?
js_output =<<-EOJS
#{js_start}
document.addEventListener("turbolinks:load", function() {
#{core_js}
});
#{js_end}
EOJS
elsif defined?(Turbo)
js_output =<<-EOJS
#{js_start}
document.addEventListener("turbo:load", function() {
#{core_js}
});
#{js_end}
EOJS
else
js_output =<<-EOJS
#{js_start}
window.addEventListener('load', function() {
#{core_js}
});
#{js_end}
EOJS
end
js_output = if request_is_xhr?
"#{js_start} #{core_js} #{js_end}"
# Turbolinks.version < 5
elsif defined?(Turbolinks) && request_is_referrer?
js_event_function(core_js, 'page:load')
# Turbolinks >= 5
elsif defined?(Turbolinks) && request_turbolinks_5_tureferrer?
js_event_function(core_js, 'turbolinks:load')
# Hotwire Turbo
elsif defined?(Turbo)
js_event_function(core_js, 'turbo:load')
else
js_event_function(core_js, 'load', 'window')
end

if defined?(raw)
return raw(js_output)
Expand All @@ -139,6 +114,18 @@ def encapsulate_js(core_js)
end
end

def js_event_function(core_js, event, target='document')
<<-EOJS
#{js_start}
var f = function(){
#{target}.removeEventListener('#{event}', f, true);
#{core_js}
};
#{target}.addEventListener('#{event}', f, true);
#{js_end}
EOJS
end

def js_start
<<-EOJS
<script type="text/javascript">
Expand Down

0 comments on commit fd5c4f7

Please sign in to comment.