余烬.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>

这两种不同的方法在余烬.js中的视图渲染方面是如何工作的。哪一个更可取,一个比另一个的用例或优势是什么。

首先,不要将 Ember 模板<script>标签放在 <div> 标签内。这不会达到您的预期。

当你使用{{view App.View1}}你告诉余烬在这里渲染App.View1的实例。它使用的模板将是您在构建 App.View 时使用的templateName。例:

<script type="text/x-handlebars" data-template-name="my-template">
  Hello World!
<script>
App.View1 = Ember.View.extend({ templateName: 'my-template' });

当您使用 {{#view App.View2}} {{/view}} 时,您告诉 ember 在此处呈现 App.View2 的实例,但以内联方式定义模板。App.View2 将没有 templateName 属性,其模板将是位于{{#view}}{{/view}}块内的模板。例:

{{#view App.View2}}
    Hello World
{{/view}}
App.View2 = Ember.View.extend();

两者都不是可取的,但命名模板允许可重用性并使代码更干净一些。结构良好的应用程序将利用这两个模板选项。当您只想向同一视图类提供一次不同的模板时,可以使用匿名/内联模板(App.View2 示例)。

最新更新