ホームページ  >  記事  >  ウェブフロントエンド  >  js_javascript スキルでイベント キュー操作関数を作成する

js_javascript スキルでイベント キュー操作関数を作成する

WBOY
WBOYオリジナル
2016-05-16 18:22:50808ブラウズ

2 日前、この一連の記事「JavaScript 非同期呼び出しフレームワークの作成 1,2,3,4,5,6」をインターネットで見ました。

非同期操作では、予期しない順序でイベントが生成される場合があります。この問題は以前にも発生しましたが、そのときは直接マルチレベルのネスト (ajax が戻った後に次のイベントをネストする) で解決するということはあまり考えませんでした。

よくお読みください。目まぐるしく見ていましたが、私の基礎知識はあまりよくないかもしれませんし、全体の状況の把握もよくありません。 d とにかくわかりにくいし、電話するほど便利ではないと思う。

次のように呼び出された場合:

varchain = Async.go(0);
chain
.next(function(){setTimeout("alert(1) ", 3000)})
.next(function(){setTimeout("alert(2)",3000)})
.next(function(){setTimeout("alert(3)",3000) }) ;

これは完璧だと思います。しかし、実際には、これが非同期呼び出しの場合は次のようになります。 Async.Operation( );
setTimeout(){operation.yield("hello"); }, 3000);

もちろん前回の記事でもう一度触れましたが、これをカプセル化することで、この不便な呼び出しはほぼ解決できると思います。



実は、私は以前にこのアイデアを持っていました。それは、自分の順序でトリガーできるクラスまたは何かを見つけることです。グループ内でそのようなクラスがあるかどうかを尋ねると、他の人は常に「文に返信して、onreadychange で実行してください」と言い、それを笑う人さえいます。当時は初心者だったので諦めました。そして今、私はまだ新人ではありますが、ついに長い道のりを歩んできました。自分の理解に従ってイベント キューを書いてみてください。

私はいつもコードを見ながら話すことに慣れているので、コードから始めて、それから私のアイデアについて話します:




コードをコピーする

コードは次のとおりです。 /**KEQueue —— イベント キュー @Author ake by 2010-04-25 http://www.cnblogs.com/akecn
@param data イベント キュー内の各イベントは、 KEQueue.status によって値が変更されない限り、このパラメータを最初のパラメータとして渡します。
@method next(Function) 次に実行されるイベント。
@method wait(Number) 一定時間待機してから次のイベントを実行します。
@method sleep() はイベント シーケンスの実行を停止します。
@method wake() は一連のイベントを継続します。
**/
var KEQueue = function(data) {
this.staticQueue = [];
this.asyncQueue = [ ];
this.result = データ;
KEQueue.prototype = {
next:function(callback, async ) {//メソッドを追加します
if(!!async) {
this.staticQueue.push("async");// 非同期メソッドの場合(遅延効果のあるメソッド)、フラグを追加します
this.asyncQueue.push(callback);//遅延メソッドのストレージ配列
}else {
this.staticQueue.push(callback);/ /直接トリガーされたメソッドのストレージ配列
}
return this;
},
wait:function(lay) {//遅延実行シーケンス
var self = this; next(function() {//Delay メソッドの追加をシミュレートします。
setTimeout(function() {
self.wake.call(self)
}, late);
},true); 🎜>return this;
},
go:function() {//追加された順にイベントを実行します
if(this.staticQueue.length == 0) return;
while(this.staticQueue.length > ; 0) {
if(this.status === "スリープ") return;

var fun = this.staticQueue.shift(); 🎜>if(typeof fun == "string" && fun == "async") {
fun = this.asyncQueue.shift();
this.result( );
}else {
fun(this.result);
}
},
sleep:function() {
this.status = "スリープ" ;
},
wake: function() {
this.status = "実行中"
this.go();
}

コードを読んだ後はすでに理解していると思いますが、コードも非常に簡単です。

実際には、配列内のメソッドを実行するループです。配列が関数でない場合、ウェイクアップ (wake()) されるまでキューの操作は停止されます。使い方もより自分の好みに傾きました。

もちろん、イベントが追加した順序で実行されたことを確認しただけかもしれませんが、他にも予想外の状況や理由がたくさんあります。ご提案やコメントがありましたら、メッセージを残してください。

以下は使用例です。




コードをコピー


コードは次のとおりです:

//Example 1 Add events and execute event queues
function show(n) {
console.log(n);
}
var o = new KEQueue("0 ");
o.next(function(d) { //The parameter is the data passed during construction. The entire event queue will return the data as a parameter.
show(d 1);
}). next(function(d) {
setTimeout(function() { //Simulate delayed operation (asynchronous operation)
show(d 2);
o.result = 0; //Change to pass The data, if not modified, will remain consistent until the last event
o.wake(); //Need to manually wake up the sequence
},2000);
},true). next(function(d){
show(d 3);
}).go();

o.next(function(d) {
setTimeout(function() { show(d 4);o.wake(); },1000);
},true).wait(1000) //Manually delay execution of the following method for 1 second
.next(function(d) {
show(d 5);
}).go();

//Example 2
o.next(function() {
show(1);
})
setTimeout(function() {
o.next(function(){
setTimeout(function() {
show(2);
o.wake();
},2000)
},true).go();
},1000);
setTimeout(function() {
o.next(function() {
show (3);
}).go();
},2000);

PS: When I went to bed at night, I suddenly wanted to say that if a complex event is added, then all If it takes a long time, will this cause an unexpected sequence of events? If each event has to be processed as an asynchronous event in the end, then this queue will not have much meaning. At most, it will help you sort out the sequence of events, nothing more. .

On the way to the company in the morning, I suddenly remembered that JavaScript operates in a single thread, and events will be blocked. If it is multi-threaded, there is probably no need to create such a queue.

I just wrote a demo and tried it, and it seems to be fine.
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。