LoginSignup
9
9

More than 5 years have passed since last update.

jQuery animte リファクタリング

Last updated at Posted at 2014-09-04
HTML
<div id="x">x</div>
<div id="y">y</div>
<div id="z">z</div>

CoffeeScript版

最初のコード

CoffeeScript
$('#x').animate
  marginLeft: 40
, ->
  $('#y').animate
    marginLeft: 40
  , ->
    $('#z').animate
      marginLeft: 40

コールバック地獄やめる

CoffeeScript
d = new $.Deferred
$('#x').animate
  marginLeft: 40
, -> d.resolve()

d.promise().then ->
  $('#y').animate
    marginLeft: 40
.then ->
  $('#z').animate
    marginLeft: 40

reduce(es6)を使う

CoffeeScript
[
  ->
    $('#x').animate
      marginLeft: 50
  ->
    $('#y').animate
      marginLeft: 50
  ->
    $('#z').animate
      marginLeft: 50
].reduce (prev, current, i) ->
  prev.then -> current()
, new $.Deferred().resolve()

JavaScript版

最初のコード

JavaScript
$('#x').animate({
  marginLeft: 40
}, function() {
  $('#y').animate({
    marginLeft: 40
  }, function() {
    $('#z').animate({
      marginLeft: 40
    });
  });
});

コールバック地獄やめる

JavaScript
var d = new $.Deferred;

$('#x').animate({
  marginLeft: 40
}, function() {
  d.resolve();
});

d.promise().then(function() {
  return $('#y').animate({
    marginLeft: 40
  });
}).then(function() {
  return $('#z').animate({
    marginLeft: 40
  });
});

reduce(es6)を使う

JavaScript
[
  function() {
    return $('#x').animate({
      marginLeft: 50
    });
  }, function() {
    return $('#y').animate({
      marginLeft: 50
    });
  }, function() {
    return $('#z').animate({
      marginLeft: 50
    });
  }
].reduce(function(prev, current, i) {
  return prev.then(function() {
    return current();
  });
}, new $.Deferred().resolve());
9
9
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
9
9