Ad

Consume Events In The Right Order

Im using channel's of pusher in a Laravel application. So when im fired an event from my controller this is received to my client, and with the pusher function I add some text with this lib https://github.com/albburtsev/jquery.typist on my front page:

channel.bind('App\\Events\\TextAdded', function(data) {
            if(data.txt){
                printPhrase(data.txt);
                i++;
            }
        });
        function printPhrase(txt) {
            $('<span>')
                    .addClass('txt_' + i)
                    .appendTo('.typist_dialog')
                    .typist({
                        text:txt,
                        speed: 15,

                    }).on('end_type.typist', function() {
console.log('end')    ;
            }).typistStop() ;
        }

    });

As you can see I can catch the event "end_type" (when the function stop writing).

The problem is that i cannot -or I've no idea howto- puts "channel.bind" on queue, and so waiting untill that the printPhrase(txt) is finished... so not showing more than one printing for time at screen...

Ad

Answer

You'll have to set up some sort of queue to make sure they don't fire until the previous one is done. This code isn't tested but should do the trick:

var printQueue = [];
var queueWorking = false;

channel.bind('App\\Events\\TextAdded', function(data) {
    if(data.txt){
        printQueue.push(data.txt);
        workQueue();
    }
});

function printPhrase(txt) {
    i++;
    $('<span>')
        .addClass('txt_' + i)
        .appendTo('.typist_dialog')
        .typist({
            text:txt,
            speed: 15,
        }).on('end_type.typist', function() {
            queueWorking = false;
            workQueue();
        }).typistStop() ;
    }

function workQueue(){
    if(printQueue.length && !queueWorking){
        queueWorking = true;
        printPhrase(printQueue.shift());
    }
}
Ad
source: stackoverflow.com
Ad