0

I have two files that use some common javascript code and the rails gon gem.

So for file 1: file1.js looks like this

$(function () {

   function a() {
    ....
   }

   $('id').on('click', function() {
     c = gon.obj1
     c.doSomething
     ....          
   })

   function otherMethods(){
   }
})

For file 2: file2.js.erb I have,

var c = abc
function a() {
  ....
}

$('id').on('click', function() {
  c.doSomething
  ....          
})

//other code

Now I am considering making my code DRY by extracting the common code in file3.js:

function a() {
  ....
}

$('id').on('click', function() {
  c.doSomething
  ....          
})

Since I am new to javascript, I am not sure about how I could populate c such that both file1.js and file2.js.erb to work correctly.

  1. How do I pass var c as an argument to the common file from file1 and file2, to the common code (let's call it file3.js)
  2. Do I just do something like <%= javascript_include_tag "file3.js" %> in file2, and similarly in file1 to access the common code?

Eventually I want to have file1.js to look like:

$(function () {

   function otherMethods(){
   }
})

and file2.js.erb to look like

//other code
gazubi
  • 561
  • 8
  • 32

1 Answers1

2

Rails uses sprockets to load javascript files from the primary application.js file. If you look at that file you'll notice how all the javascript files are loaded with require_tree .. You can copy this technique in your file3.js like so.

file3.js

//=require file1
//=require file2

// your code here...

In your first example the function a() won't be available globally without adding it to window.

file1.js

window.a = a;
Baylor Rae'
  • 3,995
  • 20
  • 39
  • but how do I send different values of c to file3 from file1 and file2? also check my updated question just so I can be more clear – gazubi Jan 04 '16 at 15:23