簡體   English   中英

如何將屬性附加到JavaScript事件?

[英]How can I append an attribute to a JavaScript event?

在行級別,我捕獲了事件並嘗試添加一個額外的參數

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

如何向事件添加屬性?

答案是您不會捕獲相同的事件,而是兩個(最初)相同的事件。 更改第一個不會更改后者。

如果要在這些事件之間傳遞數據,則需要將該數據存儲在其他位置(例如,閉包,或者如果您不關心范圍,請將其保存在window對象中)。

我知道將數據傳遞給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'
      }
   }
}

建議您不要在主視圖中捕獲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); 
  }

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM