Backbone视图中的事件

时间:2013-05-16 08:18:12

标签: javascript backbone.js backbone-views backbone-events

我的backbone.js应用程序有一组项目。集合和每个项目的视图按预期呈现。

每个项目都有两个动作,让我们说A和B.如何在我的ItemView类中挂钩事件监听器,以便我可以处理动作A和B?

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>

1 个答案:

答案 0 :(得分:1)

这条线似乎是问题所在:

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

我用它来完成它的工作:

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

注意我更改了许多其他内容以使其在本地工作,这可能是也可能不是其他问题。

  • 视图需要指定模板。
  • <a>标记包含按钮。
  • 必须更改JSON.Stringify(event)do functions。

工作代码:

    <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>
相关问题