2
myApp.onPageInit("page", function(page) {
    $$('#ajax_step1').on('submitted', function(e) {
        mainView.router.loadPage('transfer1');
    });

    $$('#ajax_step2').on('submitted', function(e) {
        mainView.router.loadPage('transfer2');
    });
    ...
});

The code inside the function seems very repetitive. How can i do the same but in a more smart way?

I tried something like this, but will not work as exptected.

for (var i = 0; i < 6; i++) {
    $$('#ajax_step'+i).on('submitted', function(e) {
        mainView.router.loadPage('transfer'+i);
    });
}
user2990084
  • 2,699
  • 9
  • 31
  • 46
  • Although your chosen method makes this question a duplicate, I would recommend having a `data-targetpage="transfer1"` attribute on your form thing, then use that attribute to determine where to go next. Use a class to bind events. – Niet the Dark Absol Feb 19 '15 at 14:52
  • @NiettheDarkAbsol that's exactly why I re-opened this. – Rory McCrossan Feb 19 '15 at 14:52

2 Answers2

4

A better approach is to use common classes along with data attributes containing meta data relevant to a specific element instance. Try something like this:

<div class="ajax_step" data-transfer="transfer1"></div>
myApp.onPageInit("page", function(page) {
    $$('.ajax_step').on('submitted', function(e) {
        mainView.router.loadPage($(this).data('transfer'));
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
3
$$('[id^=ajax_step]').on('submitted', function(e) {
    mainView.router.loadPage('transfer'+this.id.slice(9));
});

'[id^=ajax_step]' selects all elements whose id starts with "ajax_step".

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758