Backbone JS - How to write a reusable component

I want to write a reusable component as part of my Backbone application. Basically I want to write a form filter helper so that I can:

  • call func inside the view js file, which will create a dropdown menu that can listen for changes and then trigger data changes and update the view.

Ultimately I would like 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 will listen for events and handle the work.

My question is, what is the standard way to create a reusable component? Google doesn't give me much and IRC # documentcloud isn't particularly active.

+3


source to share


1 answer


Based on the information you provided in your question, it is not easy to tell how your particular component would be best component. One powerful reuse strategy, however, is mixins .

You just define methods in a simple object literal like:

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

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

      

And then you can mix them with any prototype View

:

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

      

Then the mixin methods will be available in all instances FooView

.



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

      

Since the mixin methods are bound to the context of the view instance, you can reference this

and boolean extension this.$el

inside the mixin methods. This will allow you to listen for view events:

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

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

      

To make methods available to all views, mix them in the prototype instead Backbone.View

:

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

      

+4


source







All Articles