When your Backbone JS View Events not Firing

This is a direct copy of this file on GitHub. I’m reproducing here because I think it is a great checklist that actually solved my problem when my view events were not firing.

I’ve been using backbone.js to > develop some javascript-heavy application recently.

I find it quite common for new comers to come into the following > problem: why ain’t my view events firing?

By “view events” I mean a events hash like the following in a > Backbone View class declaration.

class Mine.Views.TasksNew extends Backbone.View
  events:
    "click #preview_button":"parse"
    
  constructor:(options)->
    super(options)
    
  parse:(e)->
    alert 'clicked'

  ...

When your events are not firing, the following is a useful > checklist to go through.

  1. Maybe you have in the previous class declaration something like “el:\$(‘#myelement’)” and expecting the View to be bound to that specific element. But be cautious! The class declaration may be executed before the page is fully loaded. (This is common since I have seen most people put the class declaration before everything else). Please try to move “el:\$(‘#myelement’)” to the spot where you instantiate the View class and maybe the problem could be solved.

  2. Maybe your “el” is too restrictive. You should be know that the objects mentioned in the events hash are restricted inside the el element.

  3. Be aware of the order inside "click #preview_button":"parse"! It’s event followed by selector followed by handler. Did you reversed the order?

  4. Trace down the code using firebug,etc. The code of backbone.js is well readable.

This checklist incorporated the bad things that has happened to me > that makes my events not firing. Hope it helps you!

My specific problem was solved after hitting the second item on the checklist. “el” was too restrictive. I had el: '#posts', so my events were being restricted to within the #posts div. I changed the el to el: '#posts', and that solved my problem of the events not being fired. I’m sure this checklist would come in handy one day.

The difference between -> and => in CoffeeScript

I had this following code:

@collection.each (post) ->
  $(@el).append @template(post.attributes)
@

I was running in an issue where @el and @template were returning Uncaught TypeError: undefined is not a function. I even created a StackOverflow question about it.

I got the template to render by using jQuery directly like so,

$('#posts').append _template.( $('#home-post-template').html() ).

So this told me that the el or template was not within the scope of the each function. I remembered I was originally referencing one of Buzzstarter’s Backbone files and I had => instead of the -> I had now. Just trying things, I switched out -> for =>. Now it was working. Of course I couldn’t switch it out without understanding why it made a difference. So to the CoffeeScript documentation about the fat-arrow. It basically passes another function passing the outer context of this into an argument. This can be better illustrated with the conversion of CoffeeScript to normal Javascript

Old CoffeeScript

    @collection.each (post) ->
      $(@el).append(@template(post.attributes))
    @

Javascript Equivalent

    this.collection.each(function(post) {
      return $(this.el).append(this.template(post.attributes));
    });
    return this;

New CoffeeScript

    @collection.each (post) =>
      $(@el).append(@template(post.attributes))
    @

Javascript Equivalent

    this.collection.each((function(_this) {
      return function(post) {
        return $(_this.el).append(_this.template(post.attributes));
      };
    })(this));
    return this;

Once I saw the Javascript of the CoffeeScript with =>, it was painfully obvious what I was doing wrong and how => solved the problem. This error was due to my unfamiliarity to CoffeeScript, but Js2Coffee is quite useful in learning the differences.

New Appreciation for Programming

I recently started a new internship at Buzzstarter working with a team of experienced developers. One of the benefits of this internship is to view how good code is written. My first two weeks involved viewing their application’s source code and using similar techniques to build an introduction project.

A specific instance of seeing good code was when I saw a class method called enum.

  def self.enum(options)
    options.each do |attr, values|
      values_method = attr.to_s.pluralize

      class_eval <<-RUBY, __FILE__, __LINE__ + 1
        def self.#{values_method}
          #{values}
        end

        def #{attr}
          self.class.#{values_method}[read_attribute(:#{attr})]
        end

        def #{attr}=(value)
          idx = self.class.#{values_method}.index(value.to_sym)
          raise 'Enum not found' unless idx

          write_attribute(:#{attr}, idx)
        end
      RUBY
    end
  end

The method uses a bit of meta-programming, or at least that’s what I think this is doing, to write attributes to the database. The difference is that the values being written to the database are integer values instead of strings. As it was explained to me, this is a feature MySQL has, but PostgreSQL does not have. This allows for both reading and writing attributes to be quicker. You would then use the the enum method like so.

enum current_status: [:off, :on]

The enum method creates a getter and setter using the attribute current_status with the value being the index of the value within the values array passed in.

There are too many instances already where I’ve read some code and was left smiling about the new technique I just learnt. Not only does viewing the application’s source code show me how good code is written, but making the introduction project has me writing better code.

I am fortunate that I have one of the engineers reviewing my code via code reviews. During these code reviews, Radil, would comment on the specific lines with what I needed to change. I would make the necessary changes until I can create a branch with the feature working, then I would create another pull request. There are about ten parts to the project, but I am still only on the third part. I can already tell there is much more for me to learn.

TinyMCE, ActiveAdmin, and Rails 4

I was installing TinyMCE so I could have a WYSIWYG editor on a textarea within ActiveAdmin when I got the following error.

No route matches [GET] "/assets/tinymce/themes/advanced/theme.js"

I found the similar issue on the tinymce-rails gem’s docs. Losing TINY mce in dev when switching from 3.5.8 to 4.0.2 in Dev

The issue was caused by a change in TinyMCE’s theme. Apparently TinyMCE 4 replaced the ‘advanced’ theme with the ‘modern’ theme. Sure enough when I edited my active_admin.js.coffee CoffeeScript file to:

#= require active_admin/base
#= require tinymce
$(document).ready ->
  tinyMCE.init
    mode: "textareas"
    theme: "modern"
    editor_selector: "tinymce_editor"
  return

That solved the issue I was having. I followed along with this answer on StackOverflow to install tinyMCE to rails.

Start of Buzzstarter Internship

I just started my internship at Buzzstarter ‘Buzzstarter is the world’s first scalable programmatic content marketing platform.’ As a trial, I am currently interning part-time and remotely, but if everything goes well, then it would become more around next month. This is my first day meeting the team via Google Hangout, and I participated in my first Scrum. I’m being on-boarded right now, but I’m learning about their development process and philosophies.

I’m currently going through the intro project they have for new devs, and I’m enjoying building this small project. Its basically a blog application using all the gems they actually use on the real Buzzstarter project. One gem I especially find enjoyable is ActiveAdmin. This is my first time using the ActiveAdmin gem, and I’m really liking it. The one thing that surprised me was not having to explicitly define the resource’s controller. ActiveAdmin handles all that for us. I’m currently only on the second part of the project, but the project’s tasks are well defined and easily researchable.

Buzzstarter intro project on GitHub

Buzzstarter uses Agile development to develop software. Although I have heard of Agile development before, I have never used the methodology directly. Despite not being familiar with Agile directly, the basic concepts I read about in the Buzzstarter wiki about Agile showed that Agile has similarities to the concepts I’ve read about in Lean Startup. Things like: Embrace Failure, Deliver Smallest Product you can, Iterate Constantly, and Collect feedback. They’re straightforward concepts after being exposed to them before.

As part of the development process, we are using various tools to help with development. We use well known tools like Pivotal Tracker, Basecamp, and GitHub. We also use tools I have never heard of up until this point. Tools like Segment.io, Flowdock, Errbit. This is one of benefits I see in working with a team. I am able to be exposed to gems and services that I would not normally be exposed to.

I’ve installed the app on my local machine successfully, and I’m looking forward for the rest of this internship.

Reach out to at least 10 people a day

I was inspired by a blog post by Michael Thomas about dropping out of college and his experiences. We are of similar age, so we share many of the same thoughts. He talks about real world learning, startups, and the subject of this blog post, network. I quote:

When I was running SkyRocket my goal was to reach out to (email, phone or voicemail) at least 10 people every day. So over the course of the last 9 months I’ve “touched” over 2,700 people and probably met about 500-750 of those people. Some of these people are CEOs of top companies like HootSuite and Mobify, which has its obvious perks, and others are thought leaders who I get to learn from.

Continue reading

Railscast 053 Handling Exceptions

GitHub Repo

Heroku App

Rack Middleware

I created this episode in order to understand how rack middleware works. There was really only one line that pertained rack middleware

config.exceptions_app = self.routes

This line is a little hack to define the Rails routes as the rack middleware app that should handle exceptions. From the routes we can then match the status error in a route and map to a controller action.

Route

match '(errors)/:status', to: 'errors#show', constraints: {status: /\d{3}/}, via: :get

This route line provided me with a few lessons. the () in a route is an optional route. A route like products/:id(/:type/:year) would match a route for the product from the id and optional add the type or year params if specified.

The constraints part about further specifies what is acceptable in a route and what is not acceptable. Here we are using regex to constrain the status param to only be 3 digits. This could be useful when getting params from the route. The constraints can be analogous to how validations works for models.

Controller

class ErrorsController < ApplicationController
  def show
    @exception = env["action_dispatch.exception"]
    respond_to do |format|
      format.html { render action: request.path[1..-1] }
      format.json { render json: {status: request.path[1..-1], error: @exception.message} }
    end
  end
end

The @exception instance variable is set to the type of exception raised. The exception is store in the environment’s action_dispatch.exception. The action responds to different formats like html or json. Therequest.pathhas[1..-1]to turn/404to404`

Railscast 052 Update through Checkboxes

The GitHub Repo

The Heroku App

This episode combines the technique shown in Episode 017 habtm checkboxes and Episode 35 Custom REST Actions to update a task’s complete attribute through checkboxes.]

Some of the differences in this episode were the methods used to update the complete attribute. In episode 035, the update_attribute() was used to update a single record. In this episode we used the update_all() method. There was a slight difference in how the update_all() method was used in the video and how it is currently used. In the video the update_all() method accepts two arguments, the attribute with updated value, plus the ids of tasks to be updated. The update_all() method has been changed to accept only one argument, the attribute with the updated value. This creates some problems in specifying which record to update. Luckily, the API for update_all showed the correct way to use the updated version of update_all().

Task.where(id: params[:task_ids]).update_all([“complete=?”, true])

We use the where() method to return tasks fitting the passed in conditional.

The params[:task_ids] were sent from the form within the view.

<%= form_tag complete_tasks_path, method: :put do  %>
  <ul>
    <% @incomplete_tasks.each do |task| %>
    <li>
      <%= check_box_tag "task_ids[]", task.id %>
      <%= task.name %>
    </li>
    <% end %>
  </ul>
  <%= submit_tag "Complete task" %>
<% end %>

Here we use the form_tag because the form is not directly editing attributes on a model. We then specify the path and method to put. I am just realizing this now, but this put should be a patch to match up with what the Rails core team has been doing in transitioning from put to patch to match with RFC’s specifications.

The next part to focus on is the <%= check_box_tag "task_ids[]", task.id %> line. We are creating checkboxes for each task with the value of the task’s id. The name for each checkbox can be specified to task_ids[] because we are using a general check_box_tag. task_ids[] allows the task_ids parameter sent from the form to be an array able to hold multiple records. This is where we get the params[:task_ids] array passed into the where() method.

Which has_many association to use?

Has and Belongs to Many Example Repo

Railscast 047 Two Many-to-Many prompted me to ask this. He showed an has_many_and_belongs_to and an has_many :through example. From what the episode, Ryan Bates seems to generally like has_many :through better because it adds flexibility. What are some of the reasons behind this conclusion?

Differences

The Rails Guides on Associations has a section about this.

For has_and_belongs_to_many the relationship is built through a join table using only two models. A has_many :through relationship creates a third model that belongs_to the two models in the relationship. The circumstances you would want a has_many :through association would be:

if you need validations, callbacks, or extra attributes on the join model.

A case where you might want to have a has_many :through associations would be if you have a feature of ‘following’ within the app. Each user has followers and following users. One relationship could be established, but both do not necessarily have to be established. In the case of followers and following users, you would actually need two relationship tables in the database. ActiveRecord provides the ability to ‘reverse’ a relationship based on what the foreign key is.

There could be a relationships table with follower_id and followed_id. To find a user’s followed users, then you would set the foreign key to the follower_id. To find a user’s followers, then you would set the foreign key to the followed_id and rename this relationship to something like reverse_relationship within the model.