Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails sharing javascript between views

In my rails application, I have a piece of javascript that is exactly duplicate between 2 of my 8 views. Where is the proper place the place the javascript?

The rails application structure places javascript in app/assets/javascripts where it has a js.coffee file for each model and a application.js file. Do I place it in the application.js file or is there a way clean way to share javascript between two .js directories?

Thanks

like image 300
GTDev Avatar asked Aug 15 '26 00:08

GTDev


2 Answers

UPDATE:

I totally misread this question and thought it was about backbone.js views, not rails views. The answer below is really something different than what was asked... maybe it will be relevant to people using backbone.js, but it doesn't really answer this question. Sorry about that!

ORIGINAL ANSWER:

What I do to share code is to create a parent class, include the code I want to share in there and then have each of the views that use it extend that class (in coffeescript lingo).

So something like (again in coffeescript):

app/assets/javascripts/base_view.js.coffee (or wherever you want to put it)

class App.BaseView
  sharedFunction: () ->
    ...

and then make the other views extend App.BaseView (or whatever you call the parent class):

app/assets/javascripts/views/view2.js.coffee

class App.MyView1 extends App.BaseView
  ... sharedFunction() ...

app/assets/javascripts/views/view2.js.coffee

class App.MyView2 extends App.BaseView
  ... sharedFunction() ...

Just make sure that the file with App.BaseView is loaded before the other views in application.rb. (If you're using require.js then the load order won't matter of course, but I'm assuming you're not.)

Also as a note, although you mention that you're only sharing "a piece of javascript", it's really better to think from the start in terms of shared modules, so that if later you want to extend that "piece of javascript" you have the framework to do it. Here's a good article on implementing modules with backbone.js.

FWIW, this is the project I'm working on where I share code with common view classes: App.Threads extends App.TranslatableFieldsView which extends App.BaseView. Notice here I'm sharing initialize code using coffeescript's super. I do the same thing for models.

like image 104
Chris Salzberg Avatar answered Aug 17 '26 15:08

Chris Salzberg


What my viewpoint is to keep that javascript in assets and include it using javascript_include_tag where it is needed For example you have put common code in assets/mycode.js.cofeee

Use it like this in your html where required

javascript_include_tag('mycode')

Thanks

like image 41
Paritosh Singh Avatar answered Aug 17 '26 14:08

Paritosh Singh