16

ここで最善のパターン/アプローチについて疑問に思っていました。これは私のルーターの関数なので、ユーザーは「quotes/:id」を押しますが、そのビューをレンダリングするには、プロジェクト、顧客、および通貨のリストが必要です。quotesEditビューをインスタンス化する前に、3 つの fetches() がすべて発生したことを確認する最善の方法は何でしょうか? ユーザーが何かをクリックしたときにすべての情報を取得することは悪い習慣と見なされますか?

    quotesEdit: function(id) {
        kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
        kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
        kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();
        //do a fetch() for the 3 above
        kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
        var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
        kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
          section: 'quotesEdit',
          model: quote[0]
        }));
    }
4

3 に答える 3

40

jQuery deferredとアンダースコアのinvokeメソッドの組み合わせがこれをエレガントに解決することがわかりました。

//call fetch on the three collections, and keep their promises
var complete = _.invoke([quotes, projects, currencies], 'fetch');

//when all of them are complete...
$.when.apply($, complete).done(function() {
   //all ready and good to go...
});
于 2013-02-19T16:55:08.133 に答える
20

お約束!具体的にはjQuery.when

次のようなことができます。

$.when(
  kf.Collections.quotes.fetch(),
  kf.Collections.projects.fetch(),
  kf.Collections.currencies.fetch()
).then(function(){
  // render your view.
});

jQuery.ajax (および拡張バックボーン フェッチ) は promise を返し、複数の promise$.whenが解決されると、コールバック関数を設定するために使用できます。

于 2013-02-19T16:55:22.063 に答える
4

Backboneは jQueryオブジェクト (promise) をfetch返します。Deferredしたがって、jQuery のwhen 関数を使用して、すべての約束が解決されるのを待つことができます。


quotesEdit: function(id) {
  kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
  kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
  kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();

  //do a fetch() for the 3 above
  var quotePromise = kf.Collections.quotes.fetch();
  var projectsPromise = kf.Collections.projects.fetch();
  var currenciesPromise = kf.collections.currencies.fetch();

  // wait for them to all return
  $.when(quotePromise, projectsPromise, currenciesPromise).then(function(){

    // do stuff here, now that all three have resolved / returned

    kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
    var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
    kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
      section: 'quotesEdit',
      model: quote[0]
    }));

  };

}

ここで、promise と jQuery の when について少し書きました。

http://lostechies.com/derickbailey/2012/03/27/providing-synchronous-asynchronous-flexibility-with-jquery-when/

http://lostechies.com/derickbailey/2012/07/19/want-to-build-win8winjs-apps-you-need-to-understand-promises/

主な主題がWin8 JSであるにもかかわらず、その2番目のリンクはまだ有効です

于 2013-02-19T16:55:29.737 に答える