Backbone this.el在本地未定义

时间:2014-04-01 16:45:32

标签: backbone.js

在index.html中

<!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
    <script src="js/jquery.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
        <script src="js/underscore.js"></script>
    <script src="js/backbone.js"></script>
    <script src="js/app/index.js"></script>
  </head>
  <body></body>
  </html>
index.js中的

  (function($){
    // **ListView class**: Our main app view.
    var ListView = Backbone.View.extend({
      el: $('body'), // attaches `this.el` to an existing element.
      // `initialize()`: Automatically called upon instantiation. Where you make all types of bindings, _excluding_ UI events, such as clicks, etc.
initialize: function(){
        _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
        console.log(this);
         this.render(); // not all views are self-rendering. This one is.
      },
      // `render()`: Function in charge of rendering the entire view in `this.el`. Needs to be manually called by the user.
      render: function(){
    console.log(this);
        $(this.el).append("<ul> <li>hello world</li> </ul>");
      }
    });

    // **listView instance**: Instantiate main app view.
    var listView = new ListView();
  })(jQuery);

如果我使用file:/// C:/Users/usr/Desktop/backbone/index.html访问它,则this.el未定义。为什么?

如果我在jsfiddle中复制粘贴相同的代码,那么它的工作原理。不确定为什么enter image description here

1 个答案:

答案 0 :(得分:4)

您的javascript代码正在html文档中存在的正文标记之前执行。将您的脚本标记直接放在结束体标记之前,如下所示:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>hello-backbonejs</title>
</head>
<body>
<!-- content here -->  

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script src="js/app/index.js"></script>
</body>
</html>

我测试了这个,它适用于我的javascript文件