Tips for dynamic CSS themes using jQuery

I recently added a dark theme to this blog, it's great for night time reading on your laptop,...

Building a simple single page application using AngularJS

I am going to walk you through building a SPA (single page application) using AngularJS, Google&#...

0
Saturday, December 1, 2012
Resetting JavaScript variables when using Turbolinks

Every time you load a new page with Turbolinks only the body of the page is replaced. This means that the JavaScript environment stays the same and any variables you've set will remain the same. Sometimes this is actually welcome behaviour as I posted previously about caching dynamic partials but sometimes you want to reset those variables since the context has changed on the new page load.

Resetting JavaScript variables

A simple work around is to just delete the variable and set it again using the Turbolinks page:load event or in a script loaded by the new page. This is the method I use for the tweet links at the bottom of my posts.

delete tweet;
var tweet = function () {
  var left = (screen.width/2)-(600/2);
  var top = (screen.height/2)-(300/2);
  window.open(
    "https://twitter.com/share?via=andruu&text=Check out #{page.title}&url=#{page_url(page.slug)}",
    "Tweet Post", "width=600,height=300,top="+top+",left="+left+""
  );
  return false;
}

You will see that I actually call delete tweet; before I set the variable. If I didn't do this the tweet variable would be set to function the first time it was called and would remain the same after loading a new page.

Tweet this post if you found it useful

Related Posts

Caching dynamic partials when using Turbolinks

Friday, November 30, 2012  ·   0

Yesterday I blogged about caching and loading dynamic partials via ajax for non stati... (continued)

Using Polytalk inside a Meteor Application

Sunday, December 9, 2012  ·   0

I've put together a simple demo that integrates Polytalk with Meteor. The app all... (continued)

Introducing Polytalk. A simple protocol which allows communication between different languages via TCP.

Monday, November 26, 2012  ·   0

Polytalk is my latest open source project. I developed it out of the need to communic... (continued)

Building a simple single page application using AngularJS

Tuesday, December 4, 2012  ·   0

I am going to walk you through building a SPA (single page application) using Angular... (continued)

0 Comments

Comment successfully added. View comment.×

Comments are now closed for this article.