0

私の backbone.js アプリにはアイテムのコレクションがあります。コレクションと各アイテムのビューは期待どおりにレンダリングされます。

各アイテムには 2 つのアクション (A と B としましょう) があります。アクション A と B を処理できるように、ItemView クラスにイベント リスナーを接続するにはどうすればよいでしょうか?

window.SourceListItemView = Backbone.View.extend({
tagName: "li",

initialize: function () {
    this.model.bind("change", this.render, this);
    this.model.bind("destroy", this.close, this);
},

render: function () {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
},

events: {
   "click .action_a": "doA",
  "click .action_b": "doB"
 },

doA: function(event) {
    alert("A clicked for " + JSON.stringify(event));
},


doB: function(event) {
    alert("B clicked for " + JSON.stringify(event));
}

});

ItemView のテンプレート

 <a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;">
     <h4><%= name %></h4>
     <button class="btn btn-primary action_a"> A</button>
     <button class="btn btn-info action_b"> B</button> 
 </a>
4

1 に答える 1

1

この行が問題のようです:

$(this.el).html(this.template(this.model.toJSON()));

これを使用して動作させました:

this.$el.html(test(this.model.toJSON()));

ローカルで動作させるために、他の多くのことを変更したことに注意してください。これは、さらに問題になる場合とそうでない場合があります。

  • ビューはテンプレートを指定する必要があります。
  • <a>タグにはボタンが含まれています。
  • JSON.Stringify(event) do 関数を変更する必要がありました。

作業コード:

    <html>

      <script src="./jquery.js"></script>
      <script src="./underscore.js"></script>
      <script src="./backbone.js"></script>

      <body>
      </body>

      <script>
        window.SourceListItemView = Backbone.View.extend({
          tagName: "li",

          initialize: function () {
              this.model.bind("change", this.render, this);
              this.model.bind("destroy", this.close, this);
          },

          template: function(data) {
            var compiled = _.template('<a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;"> <h4><%= name %></h4> </a> <button class="btn btn-primary action_a"> A</button> <button class="btn btn-info action_b"> B</button>');
            return compiled;
          },

          render: function () {
              var test = this.template();
              this.$el.html(test(this.model.toJSON()));
              return this;
          },

          events: {
            "click .action_a": "doA",
            "click .action_b": "doB"
          },

          doA: function(event) {
              alert("A clicked for " + JSON.stringify(event));
          },


          doB: function(event) {
              alert("B clicked for " + $(event.srcElement).html());
          }
        });

        testModel = new Backbone.Model({id: 1, name: 'Elias'});
        testRow = new SourceListItemView({model: testModel});
        $('body').append(testRow.render().$el);
      </script>
    </html>
于 2013-05-16T17:28:05.533 に答える