如何将属性附加到JavaScript事件?

时间:2012-02-16 12:35:30

标签: javascript jquery events backbone.js

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

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

如何将属性附加到事件?

3 个答案:

答案 0 :(得分:1)

答案是你没有捕获相同的事件,而是捕获两个(最初)相同的事件。改变第一个并不会改变后者。

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

答案 1 :(得分:0)

我知道有两种方法可以将数据传递给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'
      }
   }
}

答案 2 :(得分:0)

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

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

在你的行的模型上触发一个自定义事件,并让父绑定到集合中的每个模型,虽然这看起来像是黑客攻击和性能损失。

我建议使用事件聚合器:

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); 
  }

});