Ember.js:如何在父路由控制器和子路由之间传递数据?

5
我正在构建一个应用程序,使用HTML5地理定位找到用户的位置。一旦获取了他们的位置,它们会在地图上标出(父级路由)。然后,他们可以选择查看在该位置周围发布的推文列表(子路由)。
因此,我需要将父级路由中检索到的坐标(存储在控制器上)传递给子路由,以便可以正确查询Twitter API。但是,我不确定如何做到这一点,甚至是否选择了最佳方法。
以下是索引控制器:
App.IndexController = Ember.ObjectController.extend({

  coords: false,

  getGeoLocation: function() {
    if (navigator.geolocation) {
        this.set('retrieving', true);
        navigator.geolocation.getCurrentPosition(
            this.locationRetrieved.bind(this),
            this.locationFailed.bind(this),
            {
                timeout: 20000
            }
        );
    } else {
        this.set('geolocation', false);
    }
  },

  locationRetrieved: function(position) {
    this.set('coords', position.coords);
    this.get('target').transitionTo('what-do-you-want-to-know');
  }
});

"WhatDoYouWantToKnow"控制器需要索引控制器。
App.WhatDoYouWantToKnowController = Ember.ObjectController.extend({

  needs: 'index',

  createMap: function() {
    var coords = this.get('controllers.index').get('coords');
    var pyrmont = new google.maps.LatLng(coords.latitude, coords.longitude);

    var map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: pyrmont,
        zoom: 8
    });

    var marker = new google.maps.Marker({
        map: map,
        position: pyrmont
    });
  }
});

这个路由有一个模板,链接到'/what-do-you-want-to-know/tweets'路由:
<p>Your location:</p>
<div id="map"></div>
<ul>
  <li>{{#linkTo 'tweets'}}Tweets{{/linkTo}}</li>
</ul>

我需要将这些坐标传递给子路由:
App.TweetsRoute = Ember.Route.extend({
   model: function() {
    return App.Tweet.find({coords:});
  }
});

我正在使用Ember Data的Basic Adapter。

1个回答

5

在路由中,这很容易实现。你可以访问所有的控制器。只需像这样使用 controllerFor 方法:

App.TweetsRoute = Ember.Route.extend({
    model: function () {
        var coords = this.controllerFor('index').get('coords');
        return App.Tweet.find({ coords: coords });
    }
});

controllerFor已经被弃用,你应该在tweetsController中使用needs: 'index' - xamenrax
@Nikita 我找不到你获取这个信息的地方。代码似乎并没有表明 controllerFor 方法已被弃用。 - louiscoquio
现在最好在控制器代码中使用新的 needs controllerName - xamenrax
3
@Nikita,最终我找到了它:Controller#controllerFor已经被弃用,而不是Route#controllerFor - louiscoquio
即使 "needs:" 已被弃用,现在你可以使用注入。例如:userController: Ember.inject.controller('user')。 - Epirocks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接