見出し画像

Bar表示 & イベント発生+後処理

var $=function(i){return document.getElementById(i)}

function Bar(id, value, color){
  this.id=id,
  this.min=0,
  this.value=value,
  this.max=value,
  this.color=color,
  this.makeBar=function(){
    return '<div class=bar id={id} style=color:{color};font-weight:bold;font-family:monospace;display:flex;align-items:center>{id}&nbsp;<div id={id}_border style=display:flex;border-style:solid;border-width:2px;border-color:{color};height:10px;width:{value}px;><div id={id}_value style=height:10px;width:{value}px;background-color:{color}></div></div></div>'.replace(/{(.*?)}/g,function(m,$){
      return {id:id, value:value, color:color}[$]
    })
  }
  this.changeValue=function(v){
    this.value=Math.max(this.min,Math.min(this.value+=v,this.max))
    $(this.id+'_value').style.width=this.value
    if(this.value==0) $(this.id).dispatchEvent(new CustomEvent('change',{detail:{name:'bar_'+this.name,value:0}}))
  }
}



var b1=new Bar('Armor', 100, '#ccc')

document.body.innerHTML+=b1.makeBar()

var b2=new Bar('Vital', 100, '#f00')

document.body.innerHTML+=b2.makeBar()


$('Vital').addEventListener('change',function(e){
  console.log(e)
  clearInterval(i)
})

var dec=function(){b2.changeValue(-10)}

var i=setInterval(dec, 1000)

Bar:バーオブジェクト(名前、最大値、色)
Bar.makeBar():バー表示メソッド
Bar.changeValue(value):バー変更メソッド

$(bar_name).addEventListener('change',function(e){ })
:バーの値が0になった時にイベントが発生 → 後処理


この記事が気に入ったらサポートをしてみませんか?