Javascript & rails

tips for js code in rails apps

Sprockets

mysterious assets gem

Inline scripts or application.js?

Paloma gem

page-specific javascript

# assets/javascripts/controllers/users_controller.js

var UsersController = Paloma.controller('Users');

// Executes when Rails User#new is executed.
UsersController.prototype.new = function(){
   alert('Hello Sexy User!' );
};


# Rails controller app/controllers/users_controller.rb:

def UsersController < ApplicationController
    def new
      # a Paloma request will automatically be created.
      @user = User.new
    end
end

Be careful with partials!!!!

#posts/index.haml

- @posts.each do |post| 
    = render 'post', post: post

#posts/_post.haml

.post
    %h2= post.name
    %span= post.create_at
    %button.remove remove

:javascript

    $('.remove').click(function(){
        ...
    })
#posts/index.haml

- @posts.each do |post| 
    = render 'post', post: post

#posts/_post.haml

.post
    %h2= post.name
    %span= post.create_at
    %button.remove remove


# assets/javascripts/posts.js
$('.remove').click(function(){
    $(this).parent().hide();
})

Event binding

To bind event to element it must be present in DOM

#posts/index.haml

%button.load-posts Show posts
// posts loaded with ajax

.posts-container

:javascript
    $('.remove').click(function(){
        ...
    });

#posts/_post.haml

.post
    %h2= post.name
    %span= post.create_at
    %button.remove remove

Event binding

possible solutions

// 1.
​$(document).on('click', '.remove', function(event) {
    $(this).parent().hide();
});​

// 2.
 Attach event on ajax success

Additional traps

  • Image loading
  • $ returns set of elements
Made with Slides.com