Tag Archives: jquery

How to do toggle functions in Backbone.js the right way

Recently a co-worker was asking me how best to implement a piece of toggle functionality in to a Backbone.js view. He was trying to replicate the usual jQuery toggle pattern within his backbone app but was getting confused and having some troubles accessing it from other views. This confusion comes from the fact that backbone suggests you create all of the view’s events using the events hash.

I’m writing this blog post because I actually had the exact same issue when I first started working with backbone so I feel it is a common issue and hopefully if you are reading this post I can shed some light on the subject for you.

Toggle functionality can be common in UI designs and usually is used to implement some kind of ability to turn something on and off or to disable then enable a piece of the UI.

There is an answer for this question on StackOverflow but personally I don’t really like the answer and would like to show you a more usable and dynamic way of creating some toggle functionality within your backbone views.

I prefer my approach below because I can easily allow other views access to my methods via a global events dispatcher or simply check the state of the object from another view and maybe display a message to the user within another view.

The ability to turn toggle functionality on and off in different places is really neat. This can easily crop up for instance when a client wants to move the button from one place to another and you find your self struggling with the move. Because we have the toggle state included as a property of the object we can easily check the current state of an element if need be, it will allow for much more complex use cases.

var View = Backbone.View.extend({
  events: {
    'click': 'toggleContent'
  },
  showmeState: true,
  toggleContent: function(){
    if (this.showmeState === false) {
      this.showText();
    } else {
      this.hideText();
    }
  },
  hideText: function() {
    this.$el.find('p').hide();
    this.showmeState = false;
  },
  showText: function() {
    this.$el.find('p').show();
    this.showmeState = true;
  }
});

Another use case for the above code would be for an Auto Sorting and Render of a collection in a live data environment.

var View = Backbone.View.extend({
  autoSortTimer: "",
  events: {
    'click': 'autoSort'
  },
  autoSorting: false,
  autoSort: function() {
    if(!this.autoSorting) {
      this.startAutoSort();
    } else {
      this.stopAutoSort();
    }
  },
  startAutoSort: function() {
    this.autoSorting = true;
    this.autoSortTimer = setInterval(function() {
      Dispatcher.trigger('resort');
    }, 1000);
    this.$el.find('#auto-sort-label').html('Auto Sort Columns - On');
  },
  stopAutoSort: function() {
    this.autoSorting = false;
    var autoSortTimer = this.autoSortTimer;
    clearInterval(autoSortTimer);
    this.autoSortTimer = "";
    this.$el.find('#auto-sort-label').html('Auto Sort Columns - Off');
  }
});

Adding a second scroll bar to jScrollPane

This week I have been writing some code to create a scroll-able container with two scroll bars, one at the top of the container and one at the bottom. This is for a live streaming stock market watch list app that I am currently working on.

Using jScrollPane for custom scroll bars makes this is a fairly easy piece of UI to create.

jScrollPane initialises and we listen for the 'jsp-initialised' event, we then start to create the second scroll bar by using the jQuery .clone() method and then assign some additional style and ID attributes. JQuery clone also clones the events which the original scroll bar had so instantly it works and we simply need to create some logic for syncing the two scroll bars together.

Once we have our second scroll bar, we can then attach some jScrollPane events so that they scroll together.

Let’s look at a working example

The following code is hosted on codepen.io.

Now let’s look at the code behind this example

First of all we need to get some CSS and JavaScript files. Then we simply create a container and add some jScrollPane classes to it.

<link type="text/css" href="http://jscrollpane.kelvinluck.com/style/jquery.jscrollpane.css" rel="stylesheet" media="all" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jScrollPane/2.0.14/jquery.jscrollpane.min.js"/>

<div class="scroll-pane horizontal-only">
  
  <p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children.</p>

  <p>And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.</p>

</div>

Some additional CSS to make the <P> tags wider than their parent container. This is so the scroll pane is needed to scroll the content.

body {
  font-family: Arial;
}

body .scroll-pane {
  height: 150px;
  width: 800px;
  background: white;
}

body .scroll-pane p {
  width: 1000px;
  margin: 0 0 10px 0;
}

body .jspHorizontalBar {
  background: #fff;
}

Above we have a standard setup for a single scroll bar container now we need to duplicate the scroll bar and attach the custom functionality. The jScrollPane events API is where we can find information on other jScrollPane events. For now we simply need to attach some code to the 'jsp-initialised' and the 'jsp-scroll-x' events.

$(document).ready(function() {

  var $bottom_bar,
      $top_bar;
 
  //Listen for the initalization event.
  $('.scroll-pane').bind('jsp-initialised', function(event) {
  
      //Locate the bottom scroller and clone it, with events
      //add ID attibute to both the top and bottom bars.
      $('.jspHorizontalBar')
      .attr('id', 'jspHorizontalBarBottom')
      .clone(true, true)
      .attr('id', 'jspHorizontalBarTop')
      .css({'position':'relative'})
      .insertBefore('.scroll-pane');
    
      $bottom_bar = $('div#jspHorizontalBarBottom').find('.jspDrag');
      $top_bar = $('div#jspHorizontalBarTop').find('.jspDrag');

  })
  //Listen for scroll events on the x axis.
  .bind('jsp-scroll-x', function(event, scrollPositionX, isAtLeft, isAtRight) {
    
      //Get the position of the bottom bar x axis and duplicate to the top bar.
      if (typeof $bottom_bar != 'undefined') {
        $top_bar.css({'left':$bottom_bar.position().left + 'px'});
      }

      //Add and remove classes to the arrow buttons.
      $('.jspArrow').removeClass('jspDisabled');

      if (isAtRight) {
        $('.jspArrowRight').addClass('jspDisabled');
      }

      if (isAtLeft) {
        $('.jspArrowLeft').addClass('jspDisabled');
      }

  })
  //Init the jScrollPane with Arrows
  .jScrollPane({

    showArrows: true

  });

});

If you have any questions about this blog post or any other please feel free to contact me via twitter.