johnthethird
6/12/2012 - 4:59 AM

Animation Test for Batman.js

Animation Test for Batman.js

<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=8" />
  <title>Batman Animate</title>
  <script type="text/javascript" src="https://raw.github.com/Shopify/batman/master/lib/es5-shim.js"></script>
  <script type="text/javascript" src="https://raw.github.com/Shopify/batman/v0.9.0/lib/batman.js"></script>
  <script type="text/javascript" src="http://coffeescript.org/extras/coffee-script.js"></script>
  <style>
  p {
    font: 12px/16px Arial;
    margin: 10px 10px 15px;
  }

  button {
    font: bold 14px/14px Arial;
    margin-left: 10px;
  }

  #grid {
    margin: 40px;
  }

  .box-view {
    width: 20px; height: 20px;
    float: left;
    position: relative;
    margin: 8px;
  }

  .box {
    border-radius: 100px;
    width: 20px; height: 10px;
    padding: 5px 0;
    color: #fff;
    font: 10px/10px Arial;
    text-align: center;
    position: absolute;
    background: #000;
  }
  </style>
</head>

<body>
  <script type="text/coffeescript">
    N = 100;

    class Box extends Batman.Object
        top: 0
        left: 0
        content: 0
        count: 0

        tick: () ->
            count = @get('count') + 1
            @set('count', count)
            @set('top', Math.sin(count / 10) * 10)
            @set('left', Math.cos(count / 10) * 10)
            @set('color', count % 255)
            @set('content', count % 100)

        @accessor 'style', ->
            "top: #{@get('top')}px; left: #{@get('left')}px;"


    window.Robin = class Robin extends Batman.App
      @batmanInit: () ->
        boxes = for i in [0..N]
          new Box({"number": i})
        Robin.set("boxes", boxes)

      @startAnimation: () ->
        Robin.set("shouldStop", false)
        @doAnimate()

      @doAnimate: () ->
        Robin.get("boxes").forEach((b) -> b.tick())
        Batman.setImmediate Robin.doAnimate unless Robin.get("shouldStop")

      @stopAnimation: () ->
        Robin.set("shouldStop", true)

      @on 'run', -> @batmanInit()

    Robin.run()
  </script>
  <button data-event-click="startAnimation">Start</button><button data-event-click="stopAnimation">Stop</button>

  <p>
      Based off of the Backbone/Ember/YUI version <a href="http://jsfiddle.net/ericf/NrpcQ/">here</a>
  </p>

  <div id="grid">
     <div class="box-view" data-foreach-box="boxes">
        <div class="box" data-bind-id="box.number" data-bind-style="box.style" data-bind="box.content"></div>
     </div>
  </div>

</body>
</html>