在Backbone Js中处理模型事件

时间:2014-12-26 07:40:31

标签: javascript jquery html ajax backbone.js

我编写了以下脚本来动态更新值而不刷新,脚本没问题但是id没有在页面中显示更新的值。但是,在Chrome浏览器控制台中,它会显示属性的更新值,但在页面中却不显示。

<!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 -->
  <!-- ========= -->

  <div id="container"></div>

  <!-- ========= -->
  <!-- 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({
    defaults: {
      listeners: 0
    }
  });

var SongView = Backbone.View.extend({
  initilize: function(){
    this.model.on("change", this.render,this);
  },

  render: function(){
    this.$el.html(this.model.get("title") + " - Listerners : " + this.model.get("listeners"));
    return this;
  }
});

var song = new Song({title: "Blue in Green"});
var songView = new SongView({el: "#container", model: song});
songView.render();
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

您似乎忘了将视图添加到html页面。在脚本中需要这样的一行:

$('body').append(songView.render().el);

您可以使用您想要的任何其他元素代替&#39; body&#39 ;.

还有一件事:你在“#34;初始化&#34;在歌曲视图中。因此,视图中的侦听器不会对更改做出反应。