Ember异步路由器:使用额外路由加载代码异步

时间:2013-07-03 08:29:26

标签: ember.js

在新的异步路由器中,您可以异步加载额外的代码。

App.ArticlesRoute = Ember.Route.extend({
  beforeModel: function() {
    if (!App.Article) {
      return $.getScript('/articles_code.js');
    }
  }
});

但是如果异步代码包含额外的路由怎么办? Ember将生成它们。但是我需要来自异步代码的代码,而不是Ember生成和注册的代码。

我提出了以下解决方案(但我对此并不满意):

App.ArticlesRoute = Ember.Route.extend({
  beforeModel: function(transition) {
    if (!App.Article) {
      var self = this;
      return $.getScript('/articles_code.js')
        .then(function () {
          return self.reRegisterRoutes(transition, "App", "Article"); //register the routes (with naming convention App.Article__________Route) from the loaded modules (dummies have been generated by Ember) and retry the transaction
        });
    }
  },

  reRegisterRoutes: function (transition, namespaceName, nameStartsWith) { 
    this.container.lookup('route:loading').teardownTopLevelView(); //teardown loading view
    var self = this;
    for (var prop in Ember.Namespace.byName(namespaceName).getOwnProperties()) { //[getOwnProperties](https://gist.github.com/adjohu/1817543)
      if (new RegExp(nameStartsWith + '.+Route', 'i').test(prop)) {
        this.reRegisterRoute(prop.replace(/Route$/, "").camelize()); 
      }
    }
    this.router.router.currentParams = transition.params; //set the parameters of the transition to the currentParams of the router
    return transition.retry(); //retry transaction
  },

  reRegisterRoute: function (routeName) {
    var route = this.container.cache.dict['route:' + routeName];
    if (route != undefined) {
      route.destroy(); //destroy generated route
      delete this.container.cache.dict['route:' + routeName]; //GC
      route = this.container.lookup('route:' + routeName); //register the async loaded route
      route.routeName = routeName; //set the routeName
    }
  }
});

有什么建议吗?

更新 @ darshan-sawardekar

我尝试了你的解决方案最终结果:

EEPD.RouteMapper.map(function () {
  this.route('home', { path: '/' });
  this.route('logout');
  this.route('login');

  this.resource('ccpr', function () { //ALL NEEDED FOR THE MENU TO WORK
    this.resource('ccprPatients', { path: '/' }, function () {
        this.route('search');
    });
    this.resource('ccprCardioArticles', { path: "/cardioarticles" });
    this.resource('ccprCardiologists', { path: "/cardiologists" });
    this.resource('ccprInfoSession', { path: "/infosession" }, function () {
        this.route('index');
    });
    this.resource('ccprPatientPresence', { path: "/patientpresence" }, function () {
    });
    this.resource('ccprPresenceOverview', { path: "/presenceoverview" });
    this.resource('ccprNextNutritionalAdvices', { path: "/nextnutritionaladvices" });
    this.resource('ccprParameter', { path: "/parameter" });
    this.resource('ccprListStaff', { path: "/liststaff" });
  });
});

然后在分开的加载文件中

EEPD.RouteMapper.map(function () {
  this.resource('ccpr', function () {
    this.resource('ccprPatients', { path: '/' }, function () {
        this.route('search');
    });
    this.resource('ccprPatient', { path: '/:ccpr_patient_id' }, function () {
        this.resource('ccprPracticeSessions', { path: '/practicesessions' }, function () {
        });
        this.resource('ccprPracticeSession', { path: '/practicesessions/:ccpr_practiceSession_id' }, function () {
            this.route('info');
            this.route('anamnese');
            this.route('medication');
            this.route('trainingModel', { path: '/trainingmodel' });
            this.route('socialEvaluation', { path: '/socialevaluation' });
            this.route('medicalFollowUp', { path: '/medicalfollowup' });
            this.resource('ccprPracticeSessionPsychologicalEvaluation', { path: '/psychologicalevaluation' }, function () {
                this.resource('ccprPracticeSessionPsychologicalEvaluationMnhds', { path: '/mnhd' });
                this.resource('ccprPracticeSessionPsychologicalEvaluationMnhd', { path: '/mnhd/:ebed_questionaire_id' });
                this.resource('ccprPracticeSessionPsychologicalEvaluationHadss', { path: '/hads' });
                this.resource('ccprPracticeSessionPsychologicalEvaluationHads', { path: '/hads/:ebed_questionaire_id' });
                this.resource('ccprPracticeSessionPsychologicalEvaluationDs14s', { path: '/ds14' });
                this.resource('ccprPracticeSessionPsychologicalEvaluationDs14', { path: '/ds14/:ebed_questionaire_id' });
            });
            this.resource('ccprPracticeSessionNutritionalAdvice', { path: '/nutritionaladvice' }, function () {
                this.resource('ccprPracticeSessionNutritionalAdviceBmi', { path: '/bmi/:ebed_nutritionBmi_id' });
                this.resource('ccprPracticeSessionNutritionalAdviceDietContact', { path: '/dietcontact/:ebed_dietContact_id' });
            });
            this.route('decision', { path: '/decision' });
            this.resource('ccprPracticeSessionApprovals', { path: '/approvals' }, function () {
                this.resource('ccprPracticeSessionApproval', { path: '/:erevalidatie_approval_id' });
            });
        });
    });
    this.resource('ccprCardioArticles', { path: "/cardioarticles" });
    this.resource('ccprCardiologists', { path: "/cardiologists" });
    this.resource('ccprInfoSession', { path: "/infosession" }, function () {
        this.route('addPatient');
    });
    this.resource('ccprPatientPresence', { path: "/patientpresence" }, function () {
        this.route('index');
        this.route('addPatient');
    });
    this.resource('ccprPresenceOverview', { path: "/presenceoverview" });
    this.resource('ccprNextNutritionalAdvices', { path: "/nextnutritionaladvices" });
    this.resource('ccprParameter', { path: "/parameter" });
    this.resource('ccprListStaff', { path: "/liststaff" });
  });
}, true);

它不起作用,只有当我将其与我的解决方案结合使用时,它才能正常工作。 我收到了像Assertion失败的错误:找不到路由ccprPracticeSession.info 和未捕获错误:没有名为ccprPracticeSession.info.index

的路由

1 个答案:

答案 0 :(得分:1)

您可以将所有路线图存储到另一个对象中,然后调用Router.map,遍历地图。像,

App.RouteMapper = Ember.Object.extend({
});

App.RouteMapper.reopenClass({
  maps: null,

  map: function(callback, reassign) {
    if (!this.maps) this.maps = new Array();

    this.maps.push(callback);
    if (reassign) {
      this.assign();
    }
  },

  assign: function() {
    var self = this;
    App.Router.map(function() {
      var routerScope = this;
      self.maps.forEach(function(map) {
        map.call(routerScope);
      });
    });
  }
});

App.RouteMapper.map(function() {
  this.route('lorem');
  this.route('ipsum');
});

子模块加载的代码调用App.RouteMapper.map,它将从存储的地图重建整个路径集。 maps与您传递给Router.map的回调相同,因此api不会更改。