How to Nested use “Require.js” with “backbone.js”?

此生再无相见时 提交于 2019-12-21 06:32:09

问题


I'm doing the application, the use of backbone.js and require.js, I would like to achieve dynamic configuration module navigation by the "backbone.router" function, here is my question?

This is my baserouter defined,I want to achieve dynamic load "backbone.view" according to "the viewPath" parameter.How can I do?

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;
});

This is the definition of the router, it work with "baserouter" to dynamically set the navigation menu.

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
  };
});

Here is the html code for the navigation menu:

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

回答1:


This method can achieve.But I'm not sure this is the best practice, and who has a better way?

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);


来源:https://stackoverflow.com/questions/10933541/how-to-nested-use-require-js-with-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!