簡體   English   中英

Ember.js對象視圖

[英]Ember.js view for object

我在Ember.js應用程序中擁有簡單的視圖,就像這樣。 每個“內容”元素均包含兩個對象,第一個和第二個:

{{#each App.myController.content}}
    {{view for content.first}}
    {{view for content.second}}
{{/each}}

我想在另一個把手模板腳本中分別為每個內容定義視圖(以便不必編寫兩次)。 如何將第一個和第二個變量傳遞給視圖?


這是一個代碼示例,請參閱http://jsfiddle.net/Zm4Xg/5/

把手

<script type="text/x-handlebars" data-template-name="contact-view">
     <div>{{name}}</div>
     <img {{bindAttr src="avatar"}} {{bindAttr alt="name"}}>
</script>

<script type="text/x-handlebars">
  {{#each App.contactsController.pair}}
    <div class="menu_vertical_group">
      {{#with this.first}}
         {{view App.contactView}}
      {{/with}}

      {{#with this.second}}
         {{view App.contactView}}
      {{/with}}

    </div>
  {{/each}}
</script>

JavaScript

App = Ember.Application.create();

App.Contact = Em.Object.extend({
    name: null,
    avatar: null
});

App.contactView = Ember.View.extend({
    templateName: 'contact-view'
});

App.contactsController = Em.ArrayController.create({
    content: [],
    initData: function(data) {
        var contacts = data.map(function(contact) {
            return App.Contact.create({
                "name": contact.name,
                "avatar": contact.avatar
            });
        });
        this.pushObjects(contacts);
    },

    pair: (function() {
        content = this.get('content');
        var result = [];
        for (ii = 0; ii < content.length; ii += 2) {
            result.pushObject({
                "first": content[ii],
                "second": content[ii + 1] ? content[ii + 1] : null
            });
        }
        return result;
    }).property('content')
});

App.contactsController.initData([{
    "name": "John Doe",
    "avatar": "/john.jpg"},
{
    "name": "Someone Else",
    "avatar": "/else.jpg"}]);​

像這樣的東西?

{{#each App.myController.content}}
    {{view MyView contentBinding="content.first"}}
    {{view MyView contentBinding="content.second"}}
{{/each}}

您可以使用templateName函數擴展View類,該函數根據模型的屬性求值為另一個視圖,如下所示:

App.customView = Ember.View.extend({
    templateName:function(){     
          if(this.get('content').get('index') === 1){
            return 'view1';
          }
          else{
            return 'view2';                               
          }
    }.property('content.index') // custom template function based on 'index' property
});

看看這個小提琴: http : //jsfiddle.net/lifeinafolder/7hnc9/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM