0

I'm having little trouble with coffee script in rails more so with principle and understanding then with my script alone.

I have such coffee script:

->
 $('form').on 'click', '.add_fields', (event) ->
 alert('my test message')

which gets compiled to

(function() {
 // Place all the behaviors and hooks related to the matching controller here.
 // All this logic will automatically be available in application.js.
 // You can use CoffeeScript in this file: http://coffeescript.org/
 $(function() {
 return $('form').on('click', '.add_fields', function(event) {
 return alert('my test message');
 });
 });
}).call(this);

The problem I have is that event never fires, when I take manually put this portion of compile code in console the event fires, but I have no way to have the outer most function. Am I using this wrong or can someone explain this to me how does call(this) works,so that I can put proper structure in coffee script?

 $(function() {
 return $('form').on('click', '.add_fields', function(event) {
 return alert('my test message');
 });
 });

Thanks.

asked Oct 28, 2018 at 21:36
3
  • 1
    Do you have turbolinks enabled? if so, wrap the $('form') bind inside a turbolinks:load event listener. Commented Oct 28, 2018 at 21:38
  • You are correct it fixed. Still would like to know how the turbolinks impacted this in general. but event works now. Answer below Commented Oct 28, 2018 at 22:18
  • 1
    Check Turbolinks doc, specially the section about that event listener un particular github.com/turbolinks/turbolinks#installing-javascript-behavior. Turbolinks does some thing on the background that makes your website trigger different events in order to provide it's functionality, you can adapt your workflow to use turbolinks or disable it if you don't want it. Read de README to be sure if you really want it before changing your code. Commented Oct 28, 2018 at 22:22

1 Answer 1

1

This is the final coffeescript which is working

$(document).on('turbolinks:load', ->
 $('form').on 'click', '.add_fields', (event) ->
 time = new Date().getTime()
 regexp = new RegExp($(this).data('fields').replace(regexp, time))
 $(this).before($(this).data('fields').replace(regexp, time))
 event.preventDefault())
answered Oct 28, 2018 at 22:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.