Using the Backbone.js router to navigate through views modularized with require.js

前端 未结 8 951
别跟我提以往
别跟我提以往 2020-12-22 23:41

I am separating my views and router into separate files with require. I then have a main.js file that instantiates the router, and also renders my default view.

My r

8条回答
  •  半阙折子戏
    2020-12-23 00:27

    I have a new solution for routing AMD modules.

    RequireJS Router https://github.com/erikringsmuth/requirejs-router

    This takes the approach of lazy loading AMD modules as you navigate to each page. With the Backbone router you need to require all of your views as dependencies up front. This loads all of your apps Javascript on the first page load. The RequireJS Router lazy loads modules as you navigate to each route.

    Example main.js used to run your app

    define([], function() {
      'use strict';
    
      // Configure require.js paths and shims
      require.config({
        paths: {
          'text': 'bower_components/requirejs-text/text',
          'router': 'bower_components/requirejs-router/router'
        }
      });
    
      // Load the router and your layout
      require(['router', 'js/layout/layoutView'], function(router, LayoutView) {
        var layoutView = new LayoutView();
        // The layout's render method should draw the header, footer, and an empty main-content section
        // then load the content section.
        // render: function() {
        //   this.$el.html(this.template({model: this.model}));
        //   router.loadCurrentRoute();
        // }
    
        // Configure the router
        router
          .registerRoutes({
            home: {path: '/', moduleId: 'home/homeView'},
            order: {path: '/order', moduleId: 'order/orderView'},
            notFound: {path: '*', moduleId: 'notFound/notFoundView'}
          })
          .on('statechange', function() {
            // Render the layout before loading the current route's module
            layoutView.render.call(layoutView);
          })
          .on('routeload', function(module, routeArguments) {
            // Attach the content view to the layoutView's main-content section
            layoutView.$('#main-content').replaceWith(new module(routeArguments).render().el);
          })
          .init({
            // We're manually calling loadCurrentRoute() from layoutView.render()
            loadCurrentRouteOnStateChange: false
          });
      );
    );
    

提交回复
热议问题