1
1

More than 5 years have passed since last update.

underscoreコードリーディング(after)

Posted at

underscoreに詳しくないので、勉強半分でソースコードを読む。

利用するバージョン

underscore.js(v1.8.3)

afterとは

underscorejs.orgのafter

こんな説明。

_.after(count, function)

Creates a version of the function that will only be run after first being called count times.
Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

var renderNotes = _.after(notes.length, render);
_.each(notes, function(note) {
  note.asyncSave({success: renderNotes});
});
// renderNotes is run once, after all notes have saved

count回数呼ばれたあとに初めて実行されるような関数を生成します。
非同期実行をいくつか行った際に、すべてが同期されたことが確実になってから行いたい場合に使いやすいです。

underscore.

コード的にはこのあたり。

 // Returns a function that will only be executed on and after the Nth call.
  _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

timesを前置デクリメントし、1未満になったらfuncを実行する

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1