Question

Spinning my wheels trying to figure this out. I have a link that when clicked retrieves a form from the server. The form has 3 buttons and 1 text input. I'm trying to get the non-submit buttons to respond to JS which they don't do after the form is returned from the server.

I've create a function in lists.js which the ajax:success is trying to call, but I'm not doing something right. I've tested the function in lists.js and I know it works, I'm just not calling it right.

Here are the relevant files. How do I activate the showPicturePicker function so it can be used after the AJAX response is inserted?

Lists.js

$("#new_list")
    .bind "ajax:success", (evt, xhr, settings) -> 
        $("#list-item").html(xhr)
        showPicturePicker

showPicturePicker = () ->
    $('#picture').click (e) ->
        e.preventDefault()
        alert "yeah, you figured it out"

$(document).ready showPicturePicker

_new.html.haml (the form returned from the server)

= form_for [@list, @item], :remote => true, :html => {:class => 'form-inline'} do |f|
  .input-append
    = f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
    %button#picture.btn
      %span.icon-camera
    %button#link.btn{:style => "font-size: 10px;"} 
      http://
  .secondary-fields{:style => "display: none"}  
    .field.margin
      = f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
    .field.margin
      = f.file_field "picture"
      = f.hidden_field "picture_cache"
  .clearfix
    = link_to "blah", "#{}", :class => "fuck-me"
  = f.submit "Add Item", :class => 'btn', :id => "add-item"

This is a problem i'll need to solve in other places as well and I appreciate the help.

Was it helpful?

Solution

application.js is wrapped with an IIFE (immediately invoked function expression) and variables defined there will not be visible in other files unless you explicitly make them available to the global scope (either by attaching them to window or some other object).

In application.js, try:

@showPicturePicker = ->
    ...
# or window.showPicturePicker = ->

"Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident."

http://coffeescript.org/#lexical_scope

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top