Javascript Parameters Function on Many Events

88 views Asked by At

I'm trying to implement hammer.js to swipe pages (like a book) and I did it. The problem is that this works

  var idHammer1 = document.getElementById("pageHoja1")
  //var hammertime = new Hammer(myElement, hammerOptionsPan);
  var objHammer1 = new Hammer(idHammer1);
  objHammer1.on('panleft panright', function(ev)
  {
    //DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
    if (ev.type==='panleft')
    {
      if (!(gSceneActual===2))
      {
        gSceneActual = 2;
        $(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
      }
    }
    else if (ev.type==='panright')
    {
    }
  });

but this doesn't:

var fSwipe1 = function(ev)
  {
    //DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
    if (ev.type==='panleft')
    {
      if (!(gSceneActual===2))
      {
        gSceneActual = 2;
        $(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
      }
    }
    else if (ev.type==='panright')
    {
    }
  }

  var idHammer1 = document.getElementById("pageHoja1")
  //var hammertime = new Hammer(myElement, hammerOptionsPan);
  var objHammer1 = new Hammer(idHammer1);
  objHammer1.on('panleft panright', fSwipe1(ev))

and this also don't work

function fSwipe1(ev)
  {
    //DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
    if (ev.type==='panleft')
    {
      if (!(gSceneActual===2))
      {
        gSceneActual = 2;
        $(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
      }
    }
    else if (ev.type==='panright')
    {
    }
  }

and since I need to add this event to many pages (variable #) I cant hardcode it... How can I make it variable inside a cycle?

Thanks!

1

There are 1 answers

3
KJ Price On

Ah, without knowing the extent of the errors, I do see:

objHammer1.on('panleft panright', fSwipe1(ev));

Here, you are rendering the function automatically, but what you actually want is to use a closure so that the function does not get rendered until the event gets hit. I'm not sure what ev represents, but if it is the event object, then this should work:

objHammer1.on('panleft panright', fSwipe1);

Where all you are doing is passing in the function that you want to be the callback and the even will automatically call this function and pass the event object as the first parameter.

A few other things that I notice:

  1. make sure that you include the javascript library for Hammer
  2. Make sure that gSceneActual is defined before it is evaluated at gSceneActual===2
  3. Make sure that jQuery library is included