HankHendrix
HankHendrix

Reputation: 295

Backbone JS - How to write a reusable component

I want to write a reusable component as part of my Backbone app. Fundamentally I want to write a form filter helper so I can:

Ultimately I'd like to be able to do something like this:

// generic view.js

// to spawn a dropdown
formFilter('select', data);

// to spawn a series of checkboxes
formFilter('checkbox', data);

Obviously the module code would listen for events and handle the work.

My question is, what is the standard way of creating a reusable component? Google isn't giving me much and the #documentcloud IRC isn't particularly active.

Upvotes: 3

Views: 1979

Answers (1)

jevakallio
jevakallio

Reputation: 35890

Based on the information you've provided in your question, it's not easy to say how your particular component would be best componentized. However, one powerful strategy for reusability is mixins.

Simply you define the methods in a simple object literal, such as:

Mixins.filterable = {
  filterForm: function(selector, data) {
    this.$(selector)...
  }
}

Mixins.sortable = {
  sortForm: function(selector) {
    this.$(selector)...
  }
}

And then you can mix them into any View's prototype:

_.extend(FooView.prototype, Mixins.filterable, Mixins.sortable);

The mixin methods will then be available in all instances of FooView.

render: function() {
  //..
  this.filterForm('select', this.model);
}

Because the mixin methods will be bound to the context of the view instance, you can refer to this, and by logical extension, this.$el, inside the mixin methods. This will enable you to listen to the view's events:

Mixins.filterable = {
  filterForm: function(selector, data) {
    this.$(selector).on('change', this._handleFilterChange);
  },

  _handleFilterChange: function(e) {
    //..
  }      
}

To make the methods available on all views, mix them into the Backbone.View prototype instead:

_.extend(Backbone.View.prototype, Mixins.filterable, Mixins.sortable);

Upvotes: 4

Related Questions