【问题标题】:How can I append an attribute to a JavaScript event?如何将属性附加到 JavaScript 事件?
【发布时间】:2012-02-16 12:35:30
【问题描述】:

在行级别我捕获事件并尝试添加一个额外的参数

onRowClick: function(e){
    console.log("Event in row");
    e.model = "test";
    console.log(e.model) // prints 'test'
}

在主视图中我再次捕捉到相同的事件

onRowClick: function(e){
    console.log("Event in main view");
    console.log(e.model) //prints undefined
}

控制台:

>Event in row
>test
>Event in main view
>undefined

如何将属性附加到事件?

【问题讨论】:

  • 你试过e.data.model吗?

标签: javascript jquery events backbone.js


【解决方案1】:

答案是你没有捕捉到 same 事件,而是两个(最初)相同的事件。改变前者不会改变后者。

如果您想在这些事件之间传递数据,则需要将该数据存储在其他位置(例如闭包,或者如果您不关心范围,请将其保存在窗口对象中)。

【讨论】:

    【解决方案2】:

    我知道有 2 种方法可以将数据传递给 jQuery 事件。与 e.data 一起使用,您可以像这样向 e.data 添加任何属性。

    http://www.barneyb.com/barneyblog/2009/04/10/jquery-bind-data/

    另一种方法是使用闭包,例如:

    function myFunc() {
       var model = 'test';      
    
       var x = {
          onRowClick: function(e){
              console.log("Event in row");
              console.log(model) // prints 'test'
          }
       }
    }
    

    【讨论】:

      【解决方案3】:

      我建议您不要在主视图中捕获 rowClick 事件,而是在行视图中捕获它,并将其传递给主干事件系统... 您的 parentview 可以绑定到它的行以捕获点击。

      有两种方法可以做到这一点,

      在行的模型上触发自定义事件,并让父级绑定到集合中的每个模型,尽管这似乎是一种 hack 和性能损失。

      我建议使用事件聚合器:

      var App = {
        events: _.extend({}, Backbone.Events);
      };
      
      var myGeneralView = Backbone.Views.extend({
      
        initialize: function() {
          _.bindAll(this, "catchMyCustomEvent";
      
          /* 
            and here you bind to that event on the event aggregator and 
            tell it to execute your custom made function when it is triggered.
      
            You can name it any way you want, you can namespace 
            custom events with a prefix and a ':'.
          */
          App.events.bind('rowView:rowClicked'); 
        },
      
        catchMyCustomEvent: function (model, e) {
          alert("this is the model that was clicked: " + model.get("myproperty"));
        }
      
        // other methods you will probably have here...
      });
      
      var myRowView = Backbone.Views.extend({
      
        tagName: "li",
      
        className: "document-row",
      
        events: {
          "click" : "myRowClicked"
        },
      
        initialize: function() {
          _.bindAll(this, "myRowClicked");
        },
      
        myRowClicked: function (e) {
      
          /*
            You pass your model and your event to the event aggregator
          */
          App.events.trigger('rowView:rowClicked', this.model, e); 
        }
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多