Create links programmatically inside an EmberJS view

Posted by Michael Gallego on Stack Overflow See other posts from Stack Overflow or by Michael Gallego
Published on 2013-06-30T10:19:08Z Indexed on 2013/06/30 10:20 UTC
Read the original article Hit count: 386

Filed under:
|

I have a pretty complex view to render which involves some kind of recursion (the typical folder/file nested list). The fact that it contains heterogeneous objects (folders and files) make it even harder to write Handlebars templates.

Therefore, the only solution I've found is to create a view, and manually fill the render buffer. I came with the following solution:

App.LibraryContentList = Ember.View.extend({
  tagName: 'ol',
  classNames: ['project-list', 'dd-list'],

  nameChanged: function() {
    this.rerender();
  }.observes('[email protected]'),

  render: function(buffer) {
    // We only start with depth of zero
    var content = this.get('content').filterProperty('depth', 0);

    content.forEach(function(item) {
      this.renderItem(buffer, item);
    }, this);
  },

  renderItem: function(buffer, item) {
    switch (item.constructor.toString()) {
      case 'Photo.Folder':
        this.renderFolder(buffer, item);
        break;
      case 'Photo.File':
        this.renderFile(buffer, item);
        break;
    }
  },

  renderFolder: function(buffer, folder) {
    buffer.push('<li class="folder dd-item">');
    buffer.push('<span class="dd-handle">' + folder.get('name') + '</span>');

    // Merge sub folders and files, and sort them by sort order
    var content = this.mergeAndSort();

    if (content.get('length') > 0) {
      buffer.push('<ol>');

      content.forEach(function(item) {
        this.renderItem(buffer, item);
      }, this);

      buffer.push('</ol>');
    }

    buffer.push('</li>');
  },

  renderFile: function(buffer, album) {
    buffer.push('<li class="album dd-item">');
    buffer.push('<span class="dd-handle">' + file.get('name') + '</span>');
    buffer.push('</li>');
  }
});

Now, what I'd like is to be able to add links so that each folder and each file is clickable and redirect to another route. But how am I supposed to do that, as I don't have access to the linkTo helper? I've tried to play with the LinkView view, but without any success. Should I register handlers manually for each item?

I've also thought about breaking that with a CollectionView instead, and splitting the content by depth so that I could render it using templates, but it seems more complicated.

Any thoughts?

© Stack Overflow or respective owner

Related posts about ember.js

Related posts about views