tips for js code in rails apps
mysterious assets 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
#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();
})
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
possible solutions
// 1.
$(document).on('click', '.remove', function(event) {
$(this).parent().hide();
});
// 2.
Attach event on ajax success