ArrayController中项目的单个视图

时间:2013-01-24 10:18:07

标签: javascript model-view-controller ember.js

我有一个ember.js模型和控制器设置如下:

//model
App.Order = Ember.Object.extend({

  content: null,

  create: function(data) {
    this.set('content', data);
    return this._super();
  }

});

//orders controller
App.ordersController = Ember.ArrayController.create({

  content: [],

  init: function() {

        var self = this;
    var orders = [];

    $.getJSON('js/data.json', function(data) {  
        data.forEach(function(item) { 
          var order = App.Order.create(item);
          orders.push(order);
        });
      self.set('content', orders);
    });
    },

  selectItem: function(data) {
    alert(data);
  }

});

使用以下视图:

{{#each App.ordersController}} 
   <div {{action selectItem target="App.ordersController"}}>{{order_number}}</div>
{{/each}}

通过点击操作打印出订单列表,提醒相应的商品。这很好用。

我想要做的是在单独的视图中显示单击的项目,最终目标是创建一个浮动对话框,其中显示了订单详细信息。我是新手,不知道应该如何实施。我有一个函数selectItem警告单击的订单,但我需要将其链接到单独的视图并打印订单详细信息。

我是否应将所选项目存储在具有相应视图的单独控制器中,并在单击selectItem时更新此项?或者我可以从ordersController更新sperate视图吗?任何建议都非常感谢。

1 个答案:

答案 0 :(得分:0)

使用路由器时,ember会为您实例化您的类。通过指定"orders"路由,查找名为orders的模板和名为OrdersController的控制器,如果找不到它,它将为您生成一个。 (我省略了控制器的清晰度)。要从json源加载模型,您可以查看ember-data。

这是一个jsfiddle所以你可以稍微摆弄一下。

你绝对应该看看here这些是对于真正帮助你的烬的指南。文档越来越好了。 :)

<强> JS:

window.App = App = Em.Application.create();

//model
App.Order = Ember.Object.extend({
    order_number: null,
});


//we create 2 routes one for all the order and one per specific order
App.Router.map(function(){
    this.resource('orders', { path: "/" });
    this.resource("order", { path: "/:order_id" });    
});

//the route supplies the model and handles the event to transition to a new route.    
App.OrdersRoute = Em.Route.extend({
    events: {
        selectItem: function (orderId) {
            //select the order by the "orderId" you want as a model for your new view.
            this.transitionTo("order", order);
        }
    },
    model: function(){
        return content; //an array containing the orders;
    }
});

//supplies the model for the "order" route by selecting one acording to the params;
App.OrderRoute = Em.Route.extend({
    model: function(params){
        return order; //select an object from the array according to the params
    },    
});

<强> HBS:

<script type="text/x-handlebars" data-template-name="orders">
    {{#each controller}} 
      <!-- this calls the event handler "selectItem" on the ordersroute -->
      <div {{action "selectItem" order_number}}>{{order_number}}</div>
    {{/each}}

    <!-- this is handled by "App.OrderRoute" -->
    <a href="#/3"/>with a direct link</a>
</script>

<script type="text/x-handlebars" data-template-name="order">
    {{content.order_number}}
    {{#linkTo "orders"}}Back to orders{{/linkTo}}
</script>