一个简单API设计

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

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,使得代码的可维护性、可扩展性降低

第二个版本

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给使用者

第三个版本

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'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值