Search code examples
javascriptonsen-ui

combining multiple javascript var into one function


I know absolutely nothing about js but I stumbled on this and was wondering if someone could help me combine these two into one. I will probably end up having about 30 of them. is it possible for all 30 vars to be combined? each customPush will push a new html.

Thank you.

var customPush1 = function (event) {
myNavigator.pushPage('pageNav2.html', { data: { cardTitle: 
event.target.textContent } })
};
var customPush2 = function (event) {
myNavigator.pushPage('pageNav3.html', { data: { cardTitle: event.target.textContent } })
};

Solution

  • yes. the plan is to have 30 buttons loading a separate html each

    In this case, I'd do it a different way, rather than creating lots of functions, I would add some data-attributes to the buttons, and use delegated events.

    But if you want to make it so that you can share code between functions. You can create a function that returns a function, and use closures to pass parameters. Below is an example.

    function makePush(url) {
      return function (event) {
        myNavigator.pushPage(url, { data: { cardTitle: 
          event.target.textContent } })
      }
    }
    
    var 
      customPush1 = makePush('pageNav2.html'),
      customPush2 = makePush('pageNav3.html');

    And here is an example of using delegated events on the buttons. It's uses jQuery as I find it quick and easy, but the same can be done without jQuery.

    $('body').on('click', '[data-custom-push]', function () {
      var page = $(this).attr('data-custom-push');
      alert('Page = ' + page);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button data-custom-push="pageNav1.html">Button 1</button> <br>
    <button data-custom-push="pageNav2.html">Button 2</button> <br>
    <button data-custom-push="pageNav3.html">Button 3</button> <br>
    <button data-custom-push="pageNav4.html">Button 4</button> <br>
    <button data-custom-push="pageNav5.html">Button 5</button> <br>
    <button data-custom-push="xyz.html">Button 6</button> <br>
    <button data-custom-push="abc.html">Button 7</button> <br>