November 12, 2012

Setting Backbone View Element Properties

When you create Views in Backbone, you often use the "tagName" and "className" attributes, like so:

var itemView = new ItemView({
  model: item,
  tagName: "li",
  className: "item"
});

A Collection of these will look like:

  • Beer
  • Wine
  • Chips

  • One of the things we do all the time in Backbone is set classes on a View's DOM element reflecting properties of its model. For example, say each item on the list has one or both of the classes "inStock" and "purchased" in addition to the class "item", so you'd want your markup to look like:

  • Beer
  • Wine
  • Chips

  • In the past I've often set these classes in the View's render method, like so:

    var ItemView = Backbone.View.extend({
      render: function(){
        var itemData = this.model.toJSON()
            itemEl = $(this.el);
    
        // render the template
        itemEl.html($.mustache($("#item-tpl").html(),itemData));
    
        // set the element classes
        if(itemData.inStock){
          itemEl.addClass("inStock");
        }
        if(itemData.purchased){
          itemEl.addClass("purchased");
        }      
      }
    });
    

    While his works fine, those render methods get big fast, and the more you can do to keep them clean, the better. One thing you can do is remove the setting of those classes to the instantiation method:

    var itemClasses = "item"  // all items get this class
                    + (item.get("inStock") ? " inStock" : "")
                    + (item.get("purchased") ? " purchased" : "");
    var itemView = new ItemView({
      model: item,
      tagName: "li",
      className: itemClasses
    });
    

    ...which leaves you with a much simpler View:

    var ItemView = Backbone.View.extend({
      render: function(){
        var itemData = this.model.toJSON()
            itemEl = $(this.el);
    
        // render the template
        itemEl.html($.mustache($("#item-tpl").html(),itemData));
    
      }
    });
    

    No comments:

    Post a Comment