简体   繁体   中英

Passing Data to event handler in Backbone View


I'm developing a web app using Backbonejs. I have a use case where I have to pass the new position of div1 to a double click event handler of a Backbone view.

My code looks like

var MyView = Backbone.Views.extend({
    events: {
    'dblclick #div1' : 'div1ClickHandler' //here I want to pass new offset for #div1
   }
});

div1ClickHandler: function()
{
......
}

var myView = new MyView({model: myModel,el : #div1});

You can do that: inside div you need to add a new field with name data-yourfieldName and from js call that:

yourFunctionName: function(e) {
    e.preventDefault();
    var email = $(e.currentTarget).data("yourfieldName");

}

You can pass widget in view itself, then you will have full control over widget.

var MyView = Backbone.Views.extend({
initialize: function(options) {
    this.widget = options.widget; // You will get widget here which you passed at the time of view creation 
}

events: {
    'dblclick #div1' : 'div1ClickHandler' //here I want to pass new offset for #div1
   }
});

div1ClickHandler: function() {
 // Query to fetch new position and dimensions using widget
  // update the respective element

}

var myView = new MyView({model: myModel, el: $('#div1'), widget: widgetInstance});

Assuming that your view element is a child element of the jquery widget, the best thing is probably to grab the values you need in the click handler:

var MyView = Backbone.Views.extend({
    events: {
    'dblclick #div1' : 'div1ClickHandler'
   }
});

div1ClickHandler: function()
{
  var $this = $(this);
  var $widget = $this.parents('.widget-selector:first');
  $this.offset($widget.offset());
  $this.height($widget.height());
  $this.width($widget.width());
}

var myView = new MyView({model: myModel,el : #div1});

If the jquery widget is always the direct parent of your view element, you can replace parents('.widget-selector:first') with parent() ; otherwise, you'll need to replace .widget-selector with a selector that will work for the jquery widget.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM