2

I'm trying to create an object and append a corresponding DOM element to which I'd like to bind an event that triggers a function. My question is: is it possible to access the object's initial values within that binded function?

function Bloc() {

    this.DOMel;
    this.ID = Math.round( Math.random() * 1000);
    this.startPosX;


    this.init = function() {
        $('#blocs-container').append( '<div class="bloc" data-id="' + this.ID + '"></div>' );

        this.DOMel = $('.bloc[data-id="' + this.ID + '"]');

        this.DOMel.bind('touchstart', function(e) {
            this.startPosX = e.originalEvent.touches[0].pageX;
        });
    }

}

Here, for instance, I'd like to access and modify this.startPosX within the function bound to the touchstart event.

Is it possible? If not, how should I work around it?

Thanks!

Stephanie D.
  • 109
  • 1
  • 10
  • possible duplicate of [How Does The \`this\` Keyword Work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Jamiec Jan 13 '15 at 10:40
  • Me thinks you'd be better of storing the `x` coordinate as data on the element, and then use the element to fetch it later, rather than using variables in a higher scope. – adeneo Jan 13 '15 at 10:43

3 Answers3

3

You could make use of this:

function Bloc() {
   var self = this;

   self.startPosX;

}

and then inside your function call it as self.startPosX.

Why the above works?

In the variable self you store the instance of the function Bloc. When you get in the anonymous function you assign to this.init the context changes and this points to the instance of this function. Hence you don't have access to the variables that you have stored to the outer context, using the this. However, using the above trick, you can you use the self to access the context in where startPosX exists.

Christos
  • 50,311
  • 8
  • 62
  • 97
1

You've lost context. Try this:

this.DOMel.bind('touchstart', function(e) {
    this.startPosX = e.originalEvent.touches[0].pageX;
}.bind(this));
Rax Wunter
  • 2,400
  • 3
  • 22
  • 28
0

I got it also working once I changed this.startPosX to var startPosX, and I guess Christos I explained the rationale why it works. Also, I wasn't able to get the touchstart event to work until I changed the line below:

 this.DOMel.bind('touchstart', function(e) { 

to

 $('.block[data-id="blocks"]').bind('touchstart', function(e) {

please note the selector is slightly different, because i created some divs for testing purposes. The Fiddle works once the mobile emulator is used for touchstart event.

jyrkim
  • 2,719
  • 1
  • 21
  • 31