Ember js,我如何从路由中使用控制器中的数组

ember js, how can i use the array in the controllers from the routes

本文关键字:控制器 数组 路由 js Ember      更新时间:2023-09-26

嗨,我是新的ember,我想使用处理一些数据从我的服务器端获取的数组。但我不知道该怎么做。下面的代码在routes.

searchList: null,
model: function() {
  // This is so that we don't refresh it all the time
  // arguably, this is a hack.
  var searchList = this.get('searchList');
  if(searchList !== null) {
    return searchList;
  }
  var self = this;
  return Ember.$.ajax({
    url: 'http://coen268.peterbergstrom.com/timezones.php',
    dataType: 'jsonp'
  }).then(function(response) {
    var cities = [];  <-----------------------this is an array of names from server side
    if (response && response.length) {
      for(var i=0; i<response.length; i++) {
        cities.push(Ember.Object.create(response[i]));
      }
    }
    /*
    cities.sort(function(a, b) {
        return a.id - b.id
    })
    */
    self.set('searchList', cities);
    return cities;

我只是想在我的控制器中使用城市变量,这样我就可以对输出进行排序,添加和重新组织到最终视图html。

多谢!

如果你的路由被调用,比如App.CitiesRoute,那么你需要像这样声明你的CitiesController:

App.CitiesController = Ember.ArrayController.extend({});

你可以用简单的控制器属性来排序,或者在this(它指的是你的ArrayController)上调用filter()时进行过滤,如Ember的指南所示,

你还可以访问ArrayController的所有函数和属性,如Ember API文档所示。

你甚至可以通过在你的ArrayController中指定itemController属性来为数组的每个项目指定一个特定的控制器,如:

App.CitiesController = Ember.ArrayController.extend({
  itemController: 'city'
});
// Here you can specify an ObjectController linked to all your items in the cities array
App.CityController = Ember.ObjectController.extend({
  cityNameLowercase: function() {
    return this.get('cityName').toLowerCase();
  }.property('cityName')
});

将绑定到数组的每个城市。