为什么不这样。$ el.append()有效吗?

时间:2013-09-07 20:53:51

标签: backbone.js

我正在尝试跟随http://addyosmani.github.io/backbone-fundamentals。我不知道$ el应该如何在一个视图中工作。

这是我的HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Dashboard</title>
  </head>

  <body>
    <h1>Dashboard</h1>

    <ol class="foo" id="recent-station">
    </ol>

    <!-- Templates -->
    <script type="text/template" id="station-template">
      <li><%= station %></li>
    </script>

    <!-- Javascript -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>

    <script src="static/js/script.js"></script>
  </body>
</html>

而script.js是:

var RecentStation = Backbone.Model.extend( {
    defaults: {
        station: "",
    },

    initialize: function() {
        console.log('initialized: ' + JSON.stringify(this));

        this.on('change', function() {
            console.log('changed: ' + JSON.stringify(this));
        })
    }
});

var RecentStationView = Backbone.View.extend( {
    tagName: 'ol',
    id: 'recent-station',

    initialize: function() {
        this.model.bind('change', _.bind(this.render, this));
    },

    render: function() {
        console.log('render');
        this.$el.append('<li>foo</li>');
        $('ol#recent-station').append('<li>bar</li>');
        return this;
    },
});

var recent = new RecentStation();
var recentView = new RecentStationView({model: recent});
recent.set('station', 'My Station');

有趣的东西发生在渲染功能中。我可以看到“渲染”记录到控制台,“bar”文本被附加到节点,但不是“foo”文本。我想这个。$ el和$('ol#recent-station')是一回事,但显然不是。我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果您未使用el属性指定dom元素,则会使用tagNameidclassNameattributes创建一个dom元素。观点。

在您的情况下,您没有在视图中指定el属性,因此您创建了一个如下所示的元素:

<ol id='recent-station'></ol>

然后,您将<li>foo</li>添加到其中,但您的视图元素仍然不在DOM中。

$('ol#recent-station')会返回html中包含的dom元素,该元素与您的视图元素不同,但具有相同的属性。

因此,在您的示例中,您需要通过提供el属性来指定现有元素。

 var RecentStationView = Backbone.View.extend( {
   // remove tagName and id
   el:'#recent-station',

   /* rest of your code below */

改变了一下,http://jsfiddle.net/DsRJH/