一个简单API设计

用一个红绿灯来学习jsAPI的设计web

CSS数组

#trafficLight > li{
        display: inline-block;
    }
    #trafficLight span{
        display: inline-block;
        width:50px;
        height: 50px;
        -webkit-border-radius:50%;
        -moz-border-radius:50%;
        border-radius:50%;
        background: gray;
        margin: 5px;
    }
    #trafficLight.stop li:nth-child(1) span{
        background: #a00;
    }
    #trafficLight.wait li:nth-child(2) span{
        background: #aaaa00;
    }
    #trafficLight.pass li:nth-child(3) span{
        background: #00aa00;
    }

HTML结构函数

<ul id="trafficLight" class="wait">
    <li><span></span></li>
    <li><span></span></li>
    <li><span></span></li>
</ul>

第一个版本的JS学习

var el = document.getElementById('trafficLight')
function rest() {
    el.className = 'wait'
    setTimeout(function(){
        el.className = "stop"
        setTimeout(function () {
            el.className = 'pass';
            setTimeout(rest, 2000)
        }, 2000)
    }, 2000)
}
window.onload = rest()

第一个版本实现了红绿灯功能,可是耦合性高+callback,使得代码的可维护性、可扩展性下降spa

第二个版本设计

var state = ['wait', 'stop', 'pass'];
  var stateIndex = 0;
  setInterval(function() {
      var lightState = state[stateIndex]
      el.className = lightState
      stateIndex = (stateIndex + 1) % state.length
  }, 2000)
第二个版本将状态放到数组里,之后想改变顺序,或者添加更多的状态,只须要操做数组元素就能够了,固然这个版本仍有问题,封装性很差,能够考虑将其放到一个函数里面,暴露出state和el给使用者

第三个版本rest

function start(el, stateList) {
      var stateIndex = 0;
      setInterval(function () {
        var lightState = state[stateIndex]
        el.className = lightState
        stateIndex = (stateIndex + 1) % state.length
      }, 2000)
    }
    start(el, ['wait','stop','pass'])
相关文章
相关标签/搜索