Cac3a
Cac3a

Reputation: 126

Rails 5 with coffee and jquery

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.

Upvotes: 0

Views: 640

Answers (1)

Cac3a
Cac3a

Reputation: 126

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())

Upvotes: 1

Related Questions