2

I can't get my head around on how to unsubscribe from events using Amplify.js. The events keep stacking up and a simple amplify.unsubscribe as per the documentation is not working.

I usually use anonymous callbacks but thought a named callback will be easier to unsubscribe. So, in the below code, i am subscribing to the 'registerInterest' event which is published after a button click.

The callback for the subscribe function initiates a form submission. If this form submit fails, and the user clicks submit again, two form submission requests are fired because the 'Subscriptions' stack in amplifyjs registered two subscriptions for 'registerInterest'. This stack just grows on everytime the submit is clicked.

I want to unsubscribe from the 'registerInterest' event and i don't want duplicate events.

amplify.subscribe('registerInterest',function postRegisterData() {
    jcl.dataManager({
        type: 'POST',
        url: jcl.registerUrl,
        data: register,
        dataType: 'json',
        successEventName: 'registerSuccess',
        contentType: 'application/json',
        errorEventName: 'registerError',
        beforeSend: function (req) {
            req.setRequestHeader( 'Token', jcl.authToken );
            req.setRequestHeader( 'SubscriberCode', jcl.subscriberCode );
        }
    });
    return false;
});

amplify.publish( 'registerInterest' );

From the docs, adding a 'return false' in the subscribe function should work but it didn't. I also tried adding the below inside the subscribe function.

amplify.unsubscribe('registerInterest',postRegisterData);
4

0 回答 0