将数据传递给Backbone中的视图Js在浏览器中看不到

时间:2014-12-25 20:49:13

标签: javascript backbone.js

我刚刚开始我的骨干教程,在第一次分配时我必须在页面上显示一些ul。我写了下面的代码,浏览器没有显示任何错误,但也没有在屏幕上显示列表。有人可以检查我的代码,我做错了。

    <!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Pass Data to Views</title>
</head>
<body>
  <!-- ========= -->
  <!-- Your HTML -->
  <!-- ========= -->

  <ul id="songs"></ul>

  <!-- ========= -->
  <!-- Libraries -->
  <!-- =========
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>  -->
  <script src="js/jquery.min.js" type="text/javascript"></script>
  <script src="js/underscore-min.js" type="text/javascript"></script>
  <script src="js/backbone-min.js" type="text/javascript"></script>
  <script src="js/backbone.localStorage-min.js" type="text/javascript"></script>
  <!-- =============== //
  <!-- Javascript code -->
  <!-- =============== -->
  <script type="text/javascript">

// Model
var Song = Backbone.Model.extend();

// Collection : just a group of Models
var Songs = Backbone.Collection.extend({
  model: Song
});

// View
var SongView = Backbone.View.extend({
  tagName: "li",
  render: function(){
    this.$el.html(this.model.get("title"));
    return this;
  }
});

var SongsView = Backbone.View.extend({
  render: function(){
    var self = this;

    this.model.each(function(song){
      var songView = new SongView({ model: song });
      self.$el.append(songView.render().$el);
    });
  }
});


// Adding Data to Models.
var songs = new Songs([
  new Song({title: "This is title One"}),
  new Song({title: "This is Title Two"}),
  new Song({title: "This is title third"})
]);

var Object_SongsView = new SongsView({el: "songs", model: songs});
Object_SongsView.render();

  </script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

应该像这样创建视图(在#的CSS选择器前面注意songs):

var Object_SongsView = new SongsView({
    el: "#songs",
    model: songs
});