【问题标题】:Events in Backbone views主干视图中的事件
【发布时间】:2013-05-16 08:18:11
【问题描述】:

我的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>

【问题讨论】:

  • 试图了解您的问题。 doA , doB 没有被解雇?是你的问题吗?

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


【解决方案1】:

这一行似乎是问题所在:

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

我用这个得到了它:

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

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

  • 视图需要指定模板。
  • &lt;a&gt; 标签包含按钮。
  • 不得不更改 JSON.Stringify(event) 的执行功能。

工作代码:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多