Elegantly passing an “click event” through multipl

2019-06-22 05:56发布

When a non-logined user clicks on a given button, I want to stop the event, collect his oauth, collect his email if i do not have it, and then execute the event.

I want to do everything in javascript because that would keep things much more simple.

This is how I am executing it, and I have 2 questions:

  1. Is there a more elegant way of doing multiple level callbacks?
  2. The way i am triggering the event at the end seems hackish. What might be a better way to do it?
  jQuery("a.callbacktesting").click(function(event){

    if (success==false){
      event.preventDefault();
      event.stopImmediatePropagation();
      authentication({endevent:event,followup:afterEmail},collectEmail, failFn);
    }
  });

  //1st level function
  function authentication(params, successFn, failFn){
      if (success=true){
        successFn(params,params.followup,failFn);
      }else{
       failFn();
      }      
  }

  //2nd level function
  function collectEmail(params, successFn, failFn){
      console.log("Collecting email");
      if (success=true){
        successFn(params);
      }else{
       failFn();
      };
  }

  //After everything is done, you want to execute this
  function afterEmail(params){
    jele=$(params.endevent.currentTarget)
    action=params.endevent.type
    jele.trigger(action);
  }

2条回答
甜甜的少女心
2楼-- · 2019-06-22 06:52

Consider storing your click event callback in a variable. When the user clicks the button, your JS first checks that it is authenticated. If it is, it executes the callback. If it is not, it passes the callback to the authentication routine as an argument. When the authentication routine is successful, it can then execute the callback.

查看更多
Explosion°爆炸
3楼-- · 2019-06-22 06:53

What's with this:

if (success = true) {

?

You realize that is setting the global variable "success" to true, correct? If you want to detect if the variable "success" is equal to true, use this:

if (success === true) {

Note the 3 equal marks.

Doing a strict translation of your code, I got this result:

//After everything is done, you want to execute this
function afterEmail(event) {
    $(event.currentTarget).trigger(event.type);
}

//2nd level function
function collectEmail(event) {
    console.log("Collecting email");
    if (success === true){
        afterEmail(event);
    } else {
        failFn();
    }
}

//1st level function
function authentication(event) {
    if (success === true) {
        collectEmail(event);
    } else {
        failFn();
    }
}

jQuery("a.callbacktesting").click(function (event) {
    if (success === false) {
        event.preventDefault();
        event.stopImmediatePropagation();

        authentication(event);
    }
});

If you're trying to trigger DOM events, then you'll need to use jQuery.trigger or similar. I'll need more information about your program in order to help more.

查看更多
登录 后发表回答