簡體   English   中英

如何將Ember.js控制器連接到視圖

[英]How to connect an Ember.js Controller to a View

我的Ember應用程序具有以下結構:

App.Router.map(function() {
    this.route('shop', { path: '/shop' });
});

App.ShopRoute = Ember.Route.extend({
    model: function() {
        return $.getJSON( "/fruits"); // this returns a json like this: { apples: [...], oranges: [...]}
    }
});

App.AppleListItemView = Ember.View.extend({
    templateName: 'apple-list-item',
    tagName: 'li',
    classNames: ['apple']
});

App.AppleListItemController = Ember.ArrayController.extend({
    color: "green",
});

接下來,當我嘗試在apple-list-item模板中使用{{color}}時,它什么也不打印。 我該如何解決?

您需要擔心您的命名。 路由器中的shop路線需要ShopRouteShopController ,但是我們ShopController ember會為您生成的路線。 shop模板。 您應該將視圖視為模板的可選擴展。 Ember始終具有index路由,因此您需要一個index模板:

<script type="text/x-handlebars" data-template-name="index">
  {{#link-to 'shop'}}shop!{{/link-to}}
</script>

還有一個帶有itemController的商店模板, each模板each向apples列表中的每個元素添加一個控制器:

<script type="text/x-handlebars" data-template-name="shop">
  SHOP! {{color}}
  <ul>
    {{#each apple in model.apples itemController='apple'}}
      <li class="apple">{{apple.model}} {{apple.color}}</li>
    {{/each}}
  </ul>
</script>

然后您的應用程序看起來像:

App = Ember.Application.create();

App.Router.map(function() {
    this.route('shop', { path: '/shop' });
});

使用ShopRoute

App.ShopRoute = Ember.Route.extend({
    model: function() {
        return { apples: [ 'grannysmith', 'pinklady' ], oranges: [ 'clementines' ]};
    }
});

還有一個AppleController用作itemController

App.AppleController = Ember.Controller.extend({
    color: function() {
      if (this.get('model') === 'grannysmith') {
        return 'green';
      }
      return 'purple';                                        
    }.property('model'),
});

看到這個jsbin

暫無
暫無

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

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