2012-10-20 91 views
2

我一直試圖在backbone.js上練習,我發現一個在線教程,我試圖遵循(http://backbonetutorials.com/what-is -a-router /),但不幸的是,我通過路由器遇到了問題。無法通過Backbone.js中的路由器訪問視圖+ RequireJS

下面是我的代碼

main.js

requirejs.config({ 
    // create local alias for package 
    paths: { 
     l   : 'my/vehicle', 
     underscore : 'vendors/underscore', 
     jqueryui : 'vendors/jquery-ui/js/jquery-ui-1.9.0.custom.min', 
     backbone : 'vendors/backbone', 
     bootstrap : 'vendors/bootstrap' 

    }, 
    shim: { 
     backbone: { 
      deps: ["underscore", "jquery"], 
      exports: "Backbone" 
     }, 

     underscore: { 
      exports: "_" 
     } 
    } 

}) 


require(['../../config'], function(core){ 

    require(["l/app"], function(App) { 

     'use strict'; 
     App.initialize(); 

    }); 

}); 

app.js

define(["jquery", "backbone", "l/router"], function($, Backbone, Router) { 

    var initialize = function(){ 
     // Pass in our Router module and call it's initialize function 

     Router.initialize(); 

    } 

    return { 
     initialize: initialize 
    }; 
}); 

router.js

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'l/views/BrowseVehicle' 
], function($, _, Backbone, BrowseVehicleView){ 

    var AppRouter = Backbone.Router.extend({ 
     routes: { 
      // Define some URL routes 
      '/browse' : 'showVehicleBrowse', 

      // Default 
      '*actions' : 'defaultAction' 
     } 
    }); 

    var initialize = function(){ 
     var app_router = new AppRouter; 
     app_router.on('showVehicleBrowse', function(){ 
      // Call render on the module we loaded in via the dependency array 
      console.log('am here'); 
      var BrowseVehicleView = new BrowseVehicleView(); 
      BrowseVehicleView.render(); 
     }); 

     app_router.on('defaultAction', function(actions){ 
      // We have no matching route, lets just log what the URL was 

      console.log('No route:', actions); 
     }); 

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

的意見/ BrowseVehicle.js

define([ 
    'jquery', 
    'underscore', 
    'backbone' 
], function($, _, Backbone){ 
    var BrowseVehicleView = Backbone.View.extend({ 
     el: $('#vehicle-browse-form'), 
     render: function(){ 
      // Using Underscore we can compile our template with data 
      console.log('I reached vehicle browse form'); 
     } 
    }); 
    // Our module now returns our view 
    return BrowseVehicleView; 
}); 

加載代碼沒有錯誤,console.log沒有在視圖中或路由功能中的路由器中打印任何內容。我試圖訪問我的URL使用URL /#/瀏覽,但沒有得到console.log語句。

任何人都可以請指教?

回答

1

在路徑{}定義中,刪除瀏覽前的正斜槓。

+0

我做了,我試圖再次訪問URL使用#/瀏覽和#browse都沒有工作。我無法在視圖中達到我的渲染功能 –

+3

在你的'on'處理程序中,它應該是'route:showVehicleBrowse' –

+0

是的,非常好..非常感謝。它的工作原理,我只需要使用route:作爲你所說的處理程序中的前綴。謝謝 –