IgnorantUser
IgnorantUser

Reputation: 307

Pass return values as arguments between Backbone View methods

I am trying to make a little application with a view that handles mousedown and mouseup jQuery events.

I have a getCoords method that returns the coordinates of a given mouse event I call that method from determineEvent, and store the coordinates of the mousedown in mouseDownCoords. It also returns the mouseDownCoords variable. The purpose of this method is to distinguish between a click and a drag event, but I ommited the code for brevity)

The method doStuff is triggered on mouseup and stores the coordinates of the mouseup in mouseUpCoords. The problem is that I don't know how to access the mouseDownCoords variable from within this method.

I though of triggering the event manually, through code, but that doesn't make much sense (triggerring a mouseup event from a mousedown eventhandler...) Also calling the determineEvent method from doStuff, doesn't make sense because I'm passing a different event to it (mouseup)

Here's my view code

var ScreenView = Backbone.View.extend({
  tagName: 'div',
  className:"screen",
  events: {
    "mousedown": "determineScreenEvent",
    "mouseup": "doStuff"
  },

  getCoords: function(e) {
    var screenOffset = this.$el.offset();
    var coords = [e.pageX - screenOffset.left, e.pageY - screenOffset.top];
    return coords;
  },

  determineEvent: function(e) {
    mouseDownCoords = this.getCoords(e);
    return mouseDownCoords;
    //code for distinguishing between click/drag
  },

  doStuff: function(e, mouseDownCoords) {
    mouseUpCoords = this.getCoords(e);
    //do stuff with mouseUpCoords and mouseDownCoords
  }

});

Any pointers would be helpful :)

Upvotes: 0

Views: 286

Answers (2)

homtg
homtg

Reputation: 1999

Store it in the view if you want a quick solution:

determineEvent: function(e) {
  this.mouseDownCoords = this.getCoords(e);
  return this.mouseDownCoords;
  //code for distinguishing between click/drag
},

doStuff: function(e, mouseDownCoords) {
  var mouseUpCoords = this.getCoords(e);
  //use this.mouseDownCoords
  //do stuff with mouseUpCoords and mouseDownCoords
}

Upvotes: 1

Badr
Badr

Reputation: 10658

W.r.t Backbone you should have a Model attached to view that will contain the necessary data which is required to render the view.

I recommend that you should add a model to view and set these mouseDownCoords and mouseUpCoords as part of that model that will be accessible within the view at any given time.

If your don't want to strictly follow Backbone way then simply store the coordinates as varibales in view but this is not recommended

Upvotes: 0

Related Questions