1

IndexedDBWeb SQL、またはWeb Storageを使用して、クライアントにデータを保存しています (または、クライアントがストレージをサポートしていない場合は AJAX にフォールバックします)。ページが読み込まれると、ストアからのデータを表示したいと思います。しかし、ストアの準備ができていない可能性があるため、DOM の準備ができているときにデータを表示できません。DOM の準備ができていない可能性があるため、ストアの準備ができているときにデータを表示できません。

明らかに、dom と store によって設定されたフラグをチェックする条件を実装することも、タイムアウトを使用することもできますが、それはずさんなようです (また、2 つ以上の条件が満たされる必要がある場合はうまくスケーリングされません)。この状況を処理するための一般的に「良い」方法はありますか? クロスブラウザー ソリューションを希望します (たとえば、動作しwatchません)。

状況の例:

// FooServiceFactory decides which storage method to use based on
// what the browser allows and returns a new instance of the
// implementation and starts initializing resources.
var fooService = FooServiceFactory.getInstance();

// DOM is ready
window.onload = function() {

    // fooService may not be ready yet depending on whether
    // storage has already been setup or if resources need to
    // be retrieved from the server. But I don't want this calling
    // JS to know about that.
    fooService.getAllFoo(request, function(response, status) {
        // do something with response
    });
};

注:私は今のところ自分の答えを受け入れましたが、これを処理するより良い方法をまだ開いています.

4

2 に答える 2

1

相互に依存する非同期処理を行う場合、通常はカウンターを使用します。

var running = 0;

function fire(){
  running++;

  //fire ajax bind callback

}

function callback(data){
  //do some stuff for this request
  if(--running == 0){
    //do special stuff that relies on all requests
  }
}

2 つのリクエストが同時に戻ってきて、両方が if 句を true と評価する可能性はほとんどありません。

于 2011-07-05T21:00:31.087 に答える
1

一部のストレージ (Web ストレージと IndexedDB 同期 API) は非同期ではないため、常にこれを追跡する必要はありません。サービスの実装にそれを単独で処理させるのが最善です。

1 つの方法は、実装で呼び出しをキューに入れ、ストアの準備ができたときにそれらを実行することです。これは、ストアの準備が整う前にユーザーがストアを「許可」する一部のクライアントでは特に重要であり、これには無期限の時間がかかる可能性があります。以下は、IndexedDB 実装の処理方法の例です。

var FooServiceIndexedDB = function() {
    var db = null;
    var queue = [];
    var dbRequest = window.indexedDB.open("footle", "All kinds of foo");

    var initStore = function() {
        // Misc housekeeping goes here...
        if (queue.length > 0) {
            // Things to do if there are queued functions
            for (var i = 0; i < queue.length; i++) {
                queue[i](); // Run queued function
            }
        }
    };

    dbRequest.onsuccess = function(dbRequestEvent) {
        db = dbRequestEvent.target.result;
        if (db.getVersion() != "1.0") {
            db.setVersion("1.0").onsuccess = function(versionEvent) {
                // Create stores/indexes
                initStore();
            };
        } else {
            initStore();
        }
    };

    // Public accessor
    this.getAllFoo = function(request, callback) {
        _getAllFoo(request, callback);
    };

    // Private accessor
    var _getAllFoo = function(request, callback) {
        if (db == null) {
            // This method was called before the store was ready
            queue.push(function() {_getAllFoo(request, callback);});
            return;
        }

        // Proceed getting foo
    };
};
于 2011-07-06T14:29:22.813 に答える