bitsbuffer
bitsbuffer

Reputation: 555

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

Upvotes: 4

Views: 2708

Answers (3)

Ben
Ben

Reputation: 10104

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.

Upvotes: 2

Sachin Jain
Sachin Jain

Reputation: 21842

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

Upvotes: 2

Ulug'bek
Ulug'bek

Reputation: 2832

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

}

Upvotes: 4

Related Questions