Sie sind auf Seite 1von 4

#1 How to organize JS in rails

#2 Blog

#3 Organizing Javascript in Rails Application with


turbolinks

link, link2

The Solution

1. Behavior that's "always on"


2. Behavior that's triggered from a user action

#4 Class Scoping

scope the body element of the layouts with the controller and action name

<body class="<%= controller_name %> <%= action_name %>">


<%= yield %>
</body>

can easily add page-specific CSS

#4 Default Application Manifest

// app/assets/javascripts/application.js

//= require jquery


//= require jquery_ujs
//= require turbolinks

if we do not do this it will auto load other js files in alphabetical order

#4 Initialization
# app/assets/javascript/init.coffee
window.App ||= {}

App.init = >
$("a, span, i, div").tooltip()

$(document).on "turbolinks:load", ->


App.init()

全局可以是使⽤App

⽤Appinitialie bootstrap tooltip

App.init()

// app/assets/javascripts/application.js

//= require jquery


//= require jquery_ujs
//= require turbolinks
//= require init

#4 "Always On" Javascript Funcionality

# app/assets/javascript/app.chart.coffee

class App.Chart
constructor: (@el) =>
# initilize some stuff

render: ->
# do some stuff

$(document).on "turbolinks:load", ->


chart = new App.Chart $("#chart")
chart.render()

#4 Structure
|
|
class definition
|
|

|
|
invocation
|
|

先定义⼀个js class

然后调⽤它

#4 Page-Specific Javascript

应为page-specific的情况不是很常⻅,所以⽤如下办法

# .......

$(document).on "turbolinks:load", ->


return unless $(".posts.index").length > 0
chart = new App.Chart $("#chart")
chart.render()

#4 User-Triggered Javascript

class⽤来做style, data-behavior ⽤来做js behavior交互

<%= link_to "Update Credit Card", "#", data: { behavior: "update-


credit-card" } %>

App.Billing =
update: ->
# do some stuff

$(document).on "click", "[data-behavior~=update-credit-card]", =>


App.Billing.update()

use on
#4 Add to Manifest

//= require jquery


//= require jquery_ujs
//= require turbolinks
//= require init
//= require app.chart
//= require app.billing

#3 Javascript inside your Rails Application: A better way

link

#2 Viedo

#3 Page Specific Javascript in Ruby on Rails

link

#2 Wiki
js document of Defining classes

#2 Search
link

Das könnte Ihnen auch gefallen