GTDev
GTDev

Reputation: 5528

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

Upvotes: 3

Views: 1061

Answers (2)

Chris Salzberg
Chris Salzberg

Reputation: 27374

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.

Upvotes: 1

Paritosh Singh
Paritosh Singh

Reputation: 6404

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

Upvotes: 1

Related Questions