【问题标题】:Access actions from within an route in Ember.js从 Ember.js 中的路由中访问操作
【发布时间】:2013-09-26 13:20:14
【问题描述】:

我正在更新以下路线:

App.SomeRoute = Ember.Route.extend({
 events: {
   getMore: function(){
     var controller = this.get('controller'),
         nextPage   = controller.get('page') + 1,
         perPage    = controller.get('perPage'),
         items;

     items = this.events.fetchPage(nextPage, perPage);
     controller.gotMore(items, nextPage);
   },

   fetchPage: function(page, perPage){
     . . . .
   }
 }
});

在大多数情况下,它工作正常。但是,events 语法已被弃用。相反,我们假设使用actions。更新效果很好,直到我到达这条线:

items = this.events.fetchPage(nextPage, perPage);

这会引发错误:

TypeError: this.events is null

不幸的是,如果我将代码更新为:

items = this.actions.fetchPage(nextPage, perPage);
=> TypeError: this.actions is null

如何从同一路由中访问操作方法?

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    还值得注意的是,您可能会将fetchPage 移出actions 散列。如果它只在“内部”使用并且不直接响应 UI 事件,那么它不需要在 actions 哈希中。然后你可以调用它:

    items = this.fetchPage(nextPage, perPage);
    

    【讨论】:

      【解决方案2】:

      您必须使用 .send() 来调用操作哈希中的函数。示例:

          App.SomeRoute = Ember.Route.extend({
           actions: {
             getMore: function(){
               var controller = this.get('controller'),
                   nextPage   = controller.get('page') + 1,
                   perPage    = controller.get('perPage'),
                   items;
      
              items = this.send('fetchPage', nextPage, perPage);
               controller.gotMore(items, nextPage);
            },
      
            fetchPage: function(page, perPage){
              .. . .
           }
         }
      });
      

      【讨论】:

      • 就是这样。谢谢!
      • FWIW,如果你想在你的一个测试中存根一个动作(例如使用 Sinon),那么你可以使用下划线访问该动作: sinon.spy(route._actions, 'getMore')不过不要在常规代码中这样做。
      【解决方案3】:

      您可以使用send(actionName, args...) 方法执行一些操作。

      在你的情况下:

      this.send('fetchPage', nextPage, perPage);
      

      【讨论】:

        猜你喜欢
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-17
        • 2012-08-09
        相关资源
        最近更新 更多