Building a tag editor with Ember.js

tl;dr: Ember.js components are amazing

For the past while I’ve been helping songspace.com build an ambitious web application with Ember.js. This is the fifth significant Ember application that I’ve worked on, and I’m often still amazed at just how well Ember deals with complexity.



Ember Components are one of many reasons for this, they very neatly allow us to create decoupled views which can be reused throughout our application. Below tag editor component which consists of 30 lines of clean JavaScript. (view the source on jsbin)

Live demo:

JS Bin on jsbin.com

30 lines of simple, focused JavaScript:

App.TagEditorComponent = Ember.Component.extend({
  keyDown: function(e) {
    if(e.which === 13) { this.send('add'); }
  },
  focus: function() {
    this.$('input').focus();
  }.on('didInsertElement'),
  actions: {
    add: function() {
      var newTags = this.get('newTags');
      if(newTags) {
        var tags = this.get('tags');
        newTags = newTags.split(',').map($.trim);

        newTags.forEach(function(tag) {
          if(tag.length > 0 && !tags.contains(tag)) {
            tags.pushObject(tag);
          }
        });
        this.set('newTags', '');
        this.focus();
      }
    },
    remove: function(tag) {
      var tags = this.get('tags'),
          index = tags.indexOf(tag);
      tags.removeAt(index);
      this.focus();
    }
  }
});

View code on jsbin.com »