Created
October 23, 2013 04:59
-
-
Save hspinks/7112821 to your computer and use it in GitHub Desktop.
One controller of the Products application that displays a grid of products, updates those products via Ajax on a form submission, then attempts to lay out the refilled container of products using Masonry. The Masonry is working fine, but fires too soon on the Ajax calls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= products.each do |p| %> | |
<div class="product"> | |
<%= image_tag p.picture.url %> | |
<div> | |
<h3><%= p.title %></h3> | |
</div> | |
</div> | |
<% end %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Div to hold grid of products fitted together with Masonry --> | |
<div id="products-grid"> | |
<%= render partial: 'products_grid', locals: { products: @products } %> # @products is the list of products to render | |
</div> | |
<!-- Form to update products via Ajax --> | |
<%= form_tag products_path, remote: true do %> | |
<%= submit_tag %> | |
<% end %> | |
<!-- Script to call Masonry on initial product load --> | |
<script> | |
$container = $("#products-grid"); | |
$container.imagesLoaded( function() { | |
$container.masonry(); | |
}); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$container = $("#products-grid"); | |
/* Fill container div with products */ | |
$container.html('<%= escape_javascript(render(partial: "products_grid", locals: {products: @products})) %>'); | |
/* When images are loaded, layout with Masonry */ | |
setTimeout( function () { | |
$container.imagesLoaded( function() { | |
$container.masonry(); | |
}); | |
}, 1); /* I forget where I saw this, but somewhere this said this setTimeout will make JS wait until UI renders on Ajax call */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProductsController < ApplicationController | |
def products | |
@products = Product.all | |
# Respond to html and js formats | |
respond_to do |format| | |
format.html | |
format.js # render products.js.erb when action called via ajax | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment