【问题标题】:tying button onclick event to Backbone View将按钮 onclick 事件绑定到主干视图
【发布时间】:2012-04-03 22:38:43
【问题描述】:

我在 Backbone 中有一个示例单页应用程序,我正在搞砸。这个想法是我有一个按钮可以触发视图的刷新。我试图让事件处理程序记住“this”作为主干视图,而不是调用它的元素。不管我读了多少文档,我似乎都无法克服这个心理障碍。

在我看来,我有

initialize: function() {'
  //i am trying to say, call render on this view when the button is clicked. I have tried all of these calls below.
  //this.$("#add-tweet-button").click(this.render); 
  //this.$("#add-button").bind("click", this.render);

}

当调用渲染函数时,'this' 元素就是按钮。我知道我缺少什么很容易,有人可以帮我解决吗?另外,这听起来像编码约定吗?

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    如果您使用视图的 'delegateEvents' 功能,范围会为您处理好:

    var yourView = Backbone.View.extend({
    
      events: {
        "click #add-tweet-button" : "render"
      },
    
      render: function() {
        // your render function
        return this;
      }
    });
    

    这仅适用于 View 的 El“下方”的元素。但是,您的示例显示了 this.$(...),所以我假设是这种情况。

    【讨论】:

      【解决方案2】:

      @Edward M Smith 是对的,尽管如果您需要处理 View 范围之外的元素的 jquery 事件,您可以这样写:

      var yourView = Backbone.View.extend({
      
          initialize: function() {
              var self = this;
              $("button").click(function () {
                    self.render.apply(self, arguments);
              });
      
          },
      
          render: function(event) {
              // this is your View here...
          }       
      
      });
      

      【讨论】:

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