How to continue event propagation after cancelling?

前端 未结 8 737
孤街浪徒
孤街浪徒 2020-12-13 11:41

When a user clicks a certain link I would like to present them with a confirmation dialog. If they click \"Yes\" I would like to continue the original navigation. One catch:

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 12:26

    I solved problem by this way on one of my projects. This example works with some basic event handling like clicks etc. Handler for confirmation must be first handler bound.

        // This example assumes clickFunction is first event handled.
        //
        // you have to preserve called function handler to ignore it 
        // when you continue calling.
        //
        // store it in object to preserve function reference     
        var ignoredHandler = {
            fn: false
        };
    
        // function which will continues processing        
        var go = function(e, el){
            // process href
            var href = $(el).attr('href');
            if (href) {
                 window.location = href;
            }
    
            // process events
            var events = $(el).data('events');
    
            for (prop in events) {
                if (events.hasOwnProperty(prop)) {
                    var event = events[prop];
                    $.each(event, function(idx, handler){
                        // do not run for clickFunction
                        if (ignoredHandler.fn != handler.handler) {
                            handler.handler.call(el, e);
                        }
                    });
                }
            }
        }
    
        // click handler
        var clickFunction = function(e){
            e.preventDefault();
            e.stopImmediatePropagation();
            MyApp.confirm("Are you sure you want to navigate away?")
               .done(go.apply(this, e));
        };
    
        // preserve ignored handler
        ignoredHandler.fn = clickFunction;
        $('.confirmable').click(clickFunction);
    
        // a little bit longer but it works :)
    

提交回复
热议问题