2

Can someone explain the subtle differences between the two following syntax?

(I am using rails and turbolinks with my coffeescript)

1) I've come across this recommended way of calling code.

windowReady = ->
  customFunction = ->
    ...code...

  jQuery ($) -> 
    ...code...

$(window).load(windowReady);
$(window).on('page:load', windowReady);

2) I've also used the following syntax with no noticeable differences in behavior.

(->
  customFunction = ->
    ...code...

  jQuery ($) -> 
    ...code...
).call this

What subtle differences should one watch out for with these two ways, and how would one address them? Is one more preferable than the other?

ahnbizcad
  • 9,810
  • 9
  • 54
  • 77
  • Are you using TurboLinks? – mu is too short Jun 27 '14 at 00:17
  • @mu is too short yessir. If there are further differences whether turbolinks is used or not, covering that would be much appreciated also. – ahnbizcad Jun 27 '14 at 00:35
  • 1
    [This answer](http://stackoverflow.com/a/18770219/479863) might be useful. TurboLinks only triggers the load even once, after that you get `page:load` events when TurboLinks switches pages. Unless you have a plugin that patches `$(document).ready(...)` of course. – mu is too short Jun 27 '14 at 02:08
  • It seems like the other syntax also behaves the same way – ahnbizcad Jun 27 '14 at 05:06
  • 1
    The only functional difference with the `windowReady` version is that it used a named function to bind functionality to two separate events. – mu is too short Jun 27 '14 at 05:25

1 Answers1

1

This is something of an apples-to-oranges comparison.

Clearly the body of the windowReady and anonymous function are the same, but the first version is using the JQuery (and I guess TurboLinks) library while the second version is (outside of the method itself) just straight JS/CS.

As written, the second version will execute the anonymous function exactly once--when then JS/CS file is first loaded and executed. The first version will execute the windowReady function every time the page:load event is fired.

Lela Jennings
  • 78
  • 1
  • 8