Gordon Potter
Gordon Potter

Reputation: 5862

Ember JS: templates, views, and components

Does anyone have a code snippet (jsfiddle, example perhaps) that puts into context the usage of templates, views and components in a single example? Looking for a practical demonstration of when and how to use to use one vs the other. Especially views and components which seem conceptually very close.

The guides suggest views when more complex event handling is required.

In particular I am interested in learning more about how you use these idiomatic approaches for better code reuse and more DRY view layer code. Especially wondering about the creation of nested view hierarchies and how to manage the event bubbling.

Upvotes: 4

Views: 429

Answers (1)

Ian
Ian

Reputation: 336

I have found that for 99% of the time templates are all you need. Views are when you need to interact with a template or have a UI thing that you want to re-use. As an example I created a view component for a tree view which had some complex user interaction that I needed to use in several different places in an app. I have also used views to handle 'infinite' scrolling with the data in a template which binds the browser scroll action to a method in the view. This then triggers a method in the controller to fetch more results when the web page is scrolled to the bottom:

App.CompoundPathwaysIndexView = Ember.View.extend({
  didInsertElement: function() {
    var view = this;
    $(window).bind("scroll", function() {
      view.didScroll();
    });
  },

  willDestroyElement: function() {
    $(window).unbind("scroll");
  },

  didScroll: function() {
    if(this.isScrolledToBottom() && !this.get('controller').get('fetching')) {
      this.get('controller').set('fetching', true);
      this.get('controller').send('fetchMore');
    }
  },

  isScrolledToBottom: function() {
    var documentHeight = $(document).height();
    var windowHeight = $(window).height();
    var top = $(document).scrollTop();
    var scrollPercent = (top/(documentHeight-windowHeight)) * 100;

    return scrollPercent > 99;
  }
});

Other examples of views are to inject script tags in to a template after it is rendered using the didInsertElement method (since it is apparently bad practice to add these in a handlebars template).

For example, activating the bootstrap typeahead functionality on a text box:

The template:

{{input type="text" placeholder="search" value=search action="query" id="search_box" class="search-query span4"}}

The view:

App.ApplicationView = Ember.View.extend({
    didInsertElement: function() {
      $('#search_box').typeahead({
        source: function (query, process) {
            $.getJSON(typeaheadUrl, { query: query }, function (data) {
                return process(data);
            })
        }
      });
    }
});

Upvotes: 3

Related Questions