user1530181
user1530181

Reputation: 3

coffeescript doesn't update dom element

I'm new to coffee script and I'm heaving an issue with binding to an event. I have a div, which is update via ajax and then I'd like to have some additional jquery events defined on the returned portion. This is all running on rails 3.2. my js.erb returns this portion fine:

$('#top_box').empty()
$('#top_box').append('<%= escape_javascript(render :partial => 'form') %>')

The form partial has one text field on which I want to some additional event handling i.e.

$('#link_long').on('click',function(){ $('#link_long').val("" );})

When I add the above line to js.erb file then everything works fine, but I wanted to see how this can be done in coffee. So, I translated that line into coffee such as

$ ->
  $('#link_long').on 'click', ->
    $('#link_long').val("")

The generated js code for coffee is

(function() {

 $(function() {
 return $('#link_long').on('click', function() {
 return $('#link_long').val("");
 });
 });

}).call(this); 

But the coffee script never works. Can someone tell me why?

Upvotes: 0

Views: 1133

Answers (1)

user24359
user24359

Reputation:

This is a bit of a guess, but you're probably binding the event before the partial has been appended. $('#link_long') won't find your element because it doesn't exist yet and so nothing happens. The break in your JS -> CS translation was probably moving the click handler into its own $ -> callback, which--again, I'm guessing here--is running before the one with the append in it. In any case, having multiple interdependent document ready handlers is asking for trouble.

The most obvious choice is bind after the append:

$('#top_box').append('<%= escape_javascript(render :partial => 'form') %>')
$('#link_long').on 'click', -> $('#link_long').val("")

Another option is to bind the document and then filter by the selector (the filtering gets done when the event is triggered, so you can bind before the selected elements exist):

$(document).on('click', '#link_long', -> $('#link_long').val(""))

Upvotes: 1

Related Questions