Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ember.js view rendering differs

Tags:

ember.js

// create Ember js app
App = Ember.Application.create();

// Create a grand parent view - without using templateName function/property
App.GrandparentView = Ember.View.extend({
  click: function() {
    console.log('Grandparent!');
  }
});

// Create a parent view by using templateName function/property
App.ParentView = Ember.View.extend({
  templateName:"parent-view",          
  click: function() {
    console.log('parent view!');
  }
});

// use the template to render the view content
<script type="text/x-handlebars" >
  {{#view App.GrandparentView}} 
    Click Grandparent View!     
  {{/view}}
</script>

// embed the view inside a div 
<div id="Parent">
  <script type="text/x-handlebars">
    {{view App.ParentView}}
  </script>
</div>

How does these two different approaches work in terms of view rendering in ember.js. Which one is preferable and whats the use case or advantage of one over the other.

like image 481
varunkaushish Avatar asked Sep 21 '26 20:09

varunkaushish


1 Answers

First, do not put your Ember template <script> tags inside of a <div> tag. That will not do what you expect.

When you use {{view App.View1}} you are telling ember to render an instance of App.View1 here. The template that it uses will be the templateName you used when building your App.View. Example:

<script type="text/x-handlebars" data-template-name="my-template">
  Hello World!
<script>

App.View1 = Ember.View.extend({ templateName: 'my-template' });

When you use {{#view App.View2}} {{/view}} you are telling ember to render an instance of App.View2 here, but defining the template inline. App.View2 will not have a templateName property, its template will be what lies inside the {{#view}}{{/view}} block. Example:

{{#view App.View2}}
    Hello World
{{/view}}

App.View2 = Ember.View.extend();

Neither is preferable, but named templates allow for reusability and make code a little cleaner. A well structured app will take advantage of both templating options. The anonymous/inline template (the App.View2 example) can be used when you want to provide different templates only once to the same view class.

like image 155
Ryan Avatar answered Sep 24 '26 06:09

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!