1

我有一个 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}}

它会打印出一个订单列表,点击操作会提醒相应的项目。这工作正常。

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

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

4

1 回答 1

0

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

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

你绝对应该在这里看看这些是 ember 的指南,它们真的可以帮助你。文档越来越好。:)

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
    },    
});

哈佛商学院:

<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>
于 2013-01-24T11:16:26.963 回答