Rails Turbolinks not firing JS on load

I’ve run into this a couple of times lately. Everything works fine when refreshing a page, but when navigating there via turbolinks the JS doesn’t work.

Here’s how I’m handling it.

Layout

Turbolinks likes to have any JavaScript in the head tag so I add a yield tag to the head in the layout.

head
  ...
  = yield :js_head
  ...

View

Then in the view I use content_for to grab the JS and drop it in the header.

= content_for :js_head do
  script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js" type="text/javascript" data-turbolinks-track="reload"

  javascript:
    function loadChart() {
      var ctx = document.getElementById('activityChart').getContext('2d');
      var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'line',

        // The data for our dataset
        data: {
          labels: #{raw @activity.map{|x| x[0].strftime("%b %d")}.to_json},
            datasets: [{
              label: "Searches",
                borderColor: 'rgb(0, 132, 255)',
                data: #{raw @activity.map{|x| x[2]}.to_json},
            },
            {
              label: "Clicks",
                borderColor: 'rgb(255, 99, 132)',
                data: #{raw @activity.map{|x| x[1]}.to_json},
            }]
        },

        // Configuration options go here
        options: {}
      });
    }

    function unloadChart() {
      document.removeEventListener('turbolinks:load', loadChart);
      document.removeEventListener('turbolinks:click', unloadChart);
    }

    document.addEventListener('turbolinks:load', loadChart);
    document.addEventListener('turbolinks:click', unloadChart);

Seems like in addition to the placement, I need to hook into the turbolinks:load event and turbolinks:click event.

The load event fires the code on page load, both when refreshing and when navigating there with a link.

The click event is used to unbind the events so they don’t continue to fire on other pages.

Seems like a common issue that would come up a lot, but maybe not.


VIM Search and Replace

Multiple file search and replace using VIM and renaming files with the command line.


Webdev like it's 1997

When I started learning to create webpages the web was fun and crazy and annoying. It was also open and easy to get started.

There are a few trends that are bringing some of that web back. I’m loving it!


To Freemium or Not Freemium?

I usually don’t write about the side projects I’m working on. In the spirit of changing that, I’m going write about my thoughts for CloudSh & the Freemium model.

CloudSh is a SAAS service providing search for static sites, or any site really, as long as the content is public.

I initially planned on having an free level, then changed my mind, then changed it again! WTF?! It’s hard working in a vacuum!


Rails JSON Serialized Fields

Using Rails 5 to serialize objects into a JSON field in the DB. We’re gonna assume we want to store some options as a JSON field on a User model. And we want an Options model to work with in code.


JS Widgets

Basic Webpack setup for creating a JS widget w/ a loading script.


Elixir Deploys with Make

This is one of the first times I’ve used make, but I regret not using it more often. It’s pretty simple to get started and really powerful. This was a mix of a lot of different resources.


Elixir and Docker

Elixir releases need to be built on the same system as they run on. Seems like Docker is perfect for building the releases and running them.

Well, it’s prefect for building the release. Running in Docker can make some of the BEAM stuff harder, like live code updates and clustering. Looks like there are some solutions for both, but for now I don’t mind just restarting the Docker containers.


Building Releases with Distillery

Seems like just running the app with mix is probably fine for now, but will make using a lot of the BEAM hard/impossible later. Also, the project has multiple apps, so making different builds for each seems like it might be a good idea.


Beanstalk with Terraform

This took the longest time to get working. Partly because of my own typos :p. But, also because I wanted to setup everything with Terraform.

The Beanstalk stack is just the basic Docker stack. I setup RDS for the database because both apps need it.


Deploying an Elixir Umbrella Application

The plan; use Distillery to build the Elixir apps in a Docker container. Then create Docker containers with the compiled apps. Use those to deploy on AWS Beanstalk. Build the AWS Beanstalk setup with Terraform. And deploy through a Makefile to automate things.

It’s a lot of setup to deploy an app!


Elixir Phoenix Partials

How to create partials in Elixir with block like syntax. Like:

= render_shared "page_header.html", title: "Listing Posts", body: fn ->
  = link "New Post", class: 'btn btn-sm btn-outline-secondary', to: post_path(@conn, :new)

Secret weapons

Startups need secret weapons. Any advantage that a startup can leverage is important. My secret weapons might not be yours, but you’ll have your own.

For software startups, the team, process, communication, and languages have the ability to accelerate the business and to be treated as secret weapons.


What Scrum got right

Scrum was a huge change in how software was built and a lot of its ideas are great, but some also have major problems.

Most of my experience is in early stage startups and may not apply as well to larger organizations, though I think a lot of it still does.


Getting started with Elixir

Phoenix is a web framework build on Elixir, which runs on the Erlang VM. Why check out another web framework & language?

IDK… the grass is always greener. There are new ideas in new frameworks. Maybe one will fit more with my personal development opinions.


CES 2018

robots

CES was about robots this year. There were a lot of toy focused robot kits that were cool. I like the Jimu kit the most.


GoBuffalo Nested Resources

Buffalo is a web framework written in Go by Mark Bates. I’ve been working more with Go and started using Buffalo. Mark has done an awesome job with it! Thanks Mark!

Pretty quickly into my app I wanted nested resources. Support for them seems pretty much there. It takes some work, but all in all it was pretty easy to get going. Here are some notes about how I approached it.


Starting cloudsh search project

cloudsh

I’m starting a new side project to learn Golang and use AWS Lambda.

The basic idea is an API that will index a website and provide a searching interface using JavaScript.

The target users are those creating static / generated sites. Sites where having a database setup doesn’t make sense.

I’m gonna run the API and processing on AWS Lambda using the awesome Apex and Up projects. I really like the serverless idea and am looking forward to trying it out.

If it sounds interesting, join the mailing list at cloudsh


jQuery welcome mat

Welcome mat for getting email addresses or promoting other things to recent visitors to your site. Hides the form after the first view for 14 days.

Needs jQuery before the following code.

jQuery(document).ready(function($) {
  var setCookie = function(key, value, days) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() +';path=/';
  }

  var getCookie = function(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
  }

  var visitedBefore = getCookie('welcome-mat-1');
  var el = $(".welcome-mat");
  el.remove();

  if (visitedBefore !== '1') {
    $("body").prepend( el );

    $("div.welcome-mat").hide().css("height", $(window).height()).slideDown(750);
    $("div.welcome-mat-content").css("margin-top", ($(window).height() - $(".welcome-mat-content").outerHeight()) / 2);

    $(window).bind("resize", function() {
      $("div.welcome-mat").css("height", $(window).height());
      $("div.welcome-mat-content").css("margin-top", ($(window).height() - $(".welcome-mat-content").outerHeight()) / 2);
    });

    $('.close-welcome-mat').on('click', function(e){
      e.preventDefault();
      $("div.welcome-mat").slideUp(500, function() { 
        $(this).hide().remove();
        $("body").scrollTop(0);
      });
    });

    setCookie('welcome-mat-1', '1', 14);
  }
});

Add the following style and HTML to the page. Doesn’t matter where, but I put it near the bottom of the page. It will vertically center the welcome-mat-content.

<style>
  .welcome-mat {
    height: 0px;
    z-index: 1100;
    display: none;
    position: relative;
    background: white;
  }
</style>

<div class="welcome-mat container">
  <div class="row welcome-mat-content">
    Whatever content you want here
  </div>
</div>

Who's Got Your Back

Explores the idea of creating a few deep relationships to help you get farther in your goals then you could by yourself. Basically, creating relationships where you can get and give honest feedback to overcome obstacles and roadblocks, some that you probably can’t see yourself.

Groups

Notes

The 4 mind sets: Candor < Vulnerability < Accountability < Generosity

9 steps

  1. Articulate your vision
  2. Find your lifeline relationships
  3. Practice the art of the long slow dinner
  4. Broaden your goal-setting strategy (learning and performance goals)
  5. Create your Personal Success Wheel
  6. Learn to fight
  7. Diagnose your weaknesses
  8. Commit to improvement
  9. Fake it till you make it then make it stick

Starting point for staring your own group: How to Conduct a Meeting (Kindle Locations 3793-3794).

Who’s Got Your Back Author: Keith Ferrazzi


The Undoing Project

This was an interesting read about where some of hte current thinking about decision-making came from. It’s more a story about the two people who worked together to create the these papers, Daniel Kahneman & Amos Tversky.

While the store was interesting, the biggest take away for me was another reminder that people do not make ration decisions. That they can be manipulated to make different choices about the same things based on how those things are presented.

I was suprised by how much push back there ideas received, even though it’s obvious that you personally make the mistakes they are talking about.

The Undoing Project Author: Michael Lewis


Brutalist Framework