Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • call a func inside a view js file which will create a drop-down which can listen to changes and then trigger changes in data and refreshes the view.

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.

like image 681
HankHendrix Avatar asked Dec 31 '25 10:12

HankHendrix


1 Answers

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);
like image 163
jevakallio Avatar answered Jan 02 '26 00:01

jevakallio