Presenters in javascript


If you find that you have a lot of complex logic in your views and helpers, presenters can help you to clean up your code by using object-oriented approach.

Presenter is a component containing user interface logic for a view. Presenters decoples logic from user interface, thus you are able to test your view logic via good old unit tests.

Imagine we have and object representing user’s profile. A first common task is to display user’s full name or username if full name doesn’t exist. A second common task is to display user’s avatar of a particular size or return a fallback.

Implement all this logic in views would be like a noodles, so it will be better to create a presenter for this purposes.

  Application.Presenters = Aplication.Presenters || {};
  (function () {
      'use strict';

      Application.Presenters.Profile = function(data) {
          this.data = data;

          return {
              avatarUrl: this.avatarUrl(32),
              fullName: this.fullName()
          }

      }

      Application.Presenters.Profile.prototype = {

          avatarUrl: function(size) {
              var avatarUrl = this.data.avatar
              if (!!avatarUrl) {
                return [avatarUrl, 'size='+ size].join('&')
              }
              else{
                return 'fallback/user/default.png&size=' + size
              }
          },

          fullName: function(){
            var fullName = this.data.name
            if (!!fullName) {
              return fullName;
            }
            else {
              return this.data.username
            }
          }

      }

  })();

The next step is in initialization of the presenter object and passing it to your compiled template

  var presenter = new Application.Presenters.Profile(profileObject);
  renderTemplate(
      yourCompiledTemplate(presenter)
  )

Here we go!

Related Posts

Golang and OpenAPI(Swagger). How to create documentation for your REST API services

Game of Code Review. How code review can improve the health of your team

Active Admin custom JavaScript for diverse pages

Simple hack to add per page JS to active admin

The easiest way to localize SPA application using polyglot.js

The simplest way to localize your modern single page application

Deploying rails apps, part 3. Configuring capistrano, nginx with puma

The third article of deployment series. Configuring capistrano, nginx with puma

Deploying rails apps, part 2. Setting up the necessary software

The second article of deployment series. Setting up the necessary software.

Deploying rails apps, part 1. Bootstrap the server

The first article of deployment series. Bootstrap the server.