A modern browser is required for security, reliability, and performance. Contact us.

Feb 12 2014

DRY up your Views in Backbone Marionette

If you are anything like me your Marionette views might looks something like this:

class Table extends Marionette.ItemView
        top: ".top"
        base: ".base"
    events: ->
        "click .top": @knock
        "click .base": @budge
    onShow: ->
        text: "this is the base of the table"

        text: "this is the top of the table"        
    budge: -> ...
    knock: -> ...

Let's take a look at that UI hash. It allows us to remove hard-coded DOM references from methods in the itemView.

But now take a look below at the events. We are repeating the same DOM selectors. This is not ideal, because if our DOM markup in the view changes, we have two places to change in our view definition logic. We should DRY this up!

Well, we are in luck, because as of Marionette v1.4.0 this problem was solved for us!

The UI hash can now be used from within the events hash definition, using a quasi-preprocessor DSL to make it all come together. So our view from before can be reduced to this.

class Table extends Marionette.ItemView
        top: ".top"
        base: ".base"
    events: ->
        "click @ui.top": @knock
        "click @ui.base": @budge

As you can see, this is much improved from what we had before and our DOM selectors are no longer repeated.

As an aside, I now find myself defining a UI hash for all of my views that use events, even if I do not use the UI hash anywhere else. The reason being that I now formalize by convention the UI hash as the place where my views create a tight coupling to their template markup.


Sam Saccone, @samccone