Andrey Khataev
Andrey Khataev

Reputation: 1343

Call function from different coffeescript file in rails

votable.coffee:

set_votable_hooks = (vote_area_name) ->
  ...

questions.coffee:

vote_area_name = 'xyz'
$(document).ready(set_votable_hooks(vote_area_name))

I want function to be called on document ready. I know that every coffee file is placed inside a function, so its contents are not available inside other. I've read that solution is to make set_votable_hooks global or use namespaces, couldn't manage them to work, because I'm new to js. But as I understand, preferred solution is to use namespaces in order to not pollute global object.

Upvotes: 2

Views: 918

Answers (1)

Andrey Khataev
Andrey Khataev

Reputation: 1343

Discovered, that first my mistake was assigning to callback - function with parameter, so I ended up with:

votable.coffee:

window.Votable ?= {}

window.Votable.set_votable_hooks = (vote_area_name) ->
  ...

questions.coffee:

load_votable = ->
  window.Votable.set_votable_hooks('.question-vote-area')

$(document).ready(load_votable)

and redefined coffee file inclusion in application.js:

...
//= require votable
//= require_tree .
...

without last step questions included on page before votable

Upvotes: 4

Related Questions