RequireJS和Backbone入门

时间:2012-12-27 00:00:33

标签: javascript backbone.js requirejs

我是Backbone和Require JS的新手。

我收到以下错误:

  

无法读取属性未定义的视图。

所以Backbone不可用,但我看不出问题出在哪里。任何帮助将不胜感激。

我有以下3个文件:

的index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script data-main="boot" src="../libs/require/require.js"></script>
  </head>
  <body>
    <div id="main">Magic!</div>
  </body>
</html>

boot.js:

require.config({
  baseUrl: "../",
  paths: {
      jquery : "libs/jquery/jquery-1.8.3.min",
      underscore : "libs/underscore/underscore-min",
      backbone : "libs/backbone/backbone-min"
  }
});

require( [ "app/views/app" ], function(AppView) {
  var app = new AppView();
});

app.js:

define([
    "jquery",
    "underscore",
    "backbone"
    ], function( $, _, Backbone ) {

    var AppView = Backbone.View.extend({
        el: $( "#main" ),
        initialize: function () {
             this.render();
        },
        render: function() {
            this.el.html("huzzah!");
        }
    });
    return AppView;

});

1 个答案:

答案 0 :(得分:3)

你需要使用shim骨干来使其与requirejs一起使用。

来自RequireJS docs

requirejs.config({
    shim: {
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        }
    }
});