如何嵌套使用“Require.js”与“Backbone.js的”?(How to Nested u

2019-07-29 19:21发布

我做的是应用程序,使用Backbone.js的和require.js的,我想用“backbone.router”功能来实现动态配置模块导航,这里是我的问题吗?

这被定义我baserouter,我想实现动态负载“backbone.view”据“viewPath” parameter.How我能做什么?

define(['require', 'underscore', 'backbone'], function(require, _, Backbone) {
  var BaseRouter = Backbone.Router.extend({
    container: "#page",
    loadView: function(viewPath) {

      **//Here require lazy loading "base/people/view.js", **
      **//I do not know how to achieve it?**
      var view = require(viewPath);//viewPath = "base/people/view";

      this._currentView = new view();
      this._currentView.render();
      $(this.container).html(this._currentView.el);
    }
  });

  return BaseRouter;
});

这是路由器的定义,它以“baserouter”工作动态设置的导航菜单。

define(['baserouter'], function(baserouter) {
  //The JSON data should come from the database,
  //These data define the navigation information for all modules.
  var navs = JSON.parse('[{"name": "people","title": "peoplemanage","view": "base/people/view"},{"name": "test","title": "testmanage","view": "pub/test/view"}]');
  var AppRouter = baserouter.extend();

  for (var i = 0, l = navs.length; i < l; i++) {
    var nav = navs[i];
    AppRouter.prototype["loadView_" + nav.name] = function() {
      var path = nav.view;
      return function() {
        AppRouter.prototype.loadView(path);
      }
    }();
  }

  var initialize = function() {
      var routes = {}
      for (var i = 0, l = navs.length; i < l; i++) {
        var nav = navs[i];
        routes[nav.name] = "loadView_" + nav.name;
      }

      var app_router = new AppRouter({
        "routes": routes
      });

      Backbone.history.start();
    };
  return {
    initialize: initialize
  };
});

下面是导航菜单的HTML代码:

<ul class="dropdown-menu">
    <li><a href="#people">people</a></li>
    <li><a href="#test">test</a></li>
</ul>

Answer 1:

这种方法可以achieve.But我不知道这是最好的做法,谁还有更好的办法?

loadView: function(viewPath) {
var _this = this;
if (this._currentView) {
    this._currentView.dispose();
}

//var view = require(viewPath);
//**This method can achieve.But I'm not sure this is the best practice, and who has a better way?**
//setTimeout(function() {
    require([viewPath], function(view) {
        _this._currentView = new view();
        _this._currentView.render();
        $("#page").html(_this._currentView.el);
    });
//}, 100);


文章来源: How to Nested use “Require.js” with “backbone.js”?