LoginSignup
2
1

More than 5 years have passed since last update.

riot.js 子tagの独立性を上げる。

Last updated at Posted at 2018-04-20

riotは親子関係を把握することが出来るが、互いのモジュールを知らないほうが独立性が上がり、並行してモジュール開発が出来る。

自分自身にトリガーを引いて(change)、第三者モジュールが変更を検知して参加者全員に知らせる。(changed)

自分自身は参加者は知らないし、誰がchangedしたのかも知らない。ただ、変更されたデータストアが投げられる。

riot.tag('ed','<div ref="code" contenteditable="plaintext-only" oninput="{input}"></div>',function(opts){
 let self=this,code=null;
 self.on('mount',()=>{code=self.refs.code})
 self.on('changed',(d)=>{ if(code.textContent!=d.ed) code.textContent=d.ed })
 self.input=()=>{ self.trigger('change',{ed:code.textContent}) }
})

第三者は最近ではデータストアそのものであることが多い。

var sys=new function(){
 riot.observable(this); 
 let self=this,cs=[],share=()=>{ cs.filter(d=>d).map(d=>d.trigger('changed',self.store))}
 //cs.filter mean fall the child.
 ,init =(d)=>{d.on('change',(o)=>{ Object.assign(self.store,o); share() })} 
 self.store={}
 self.on('join',(me)=>{ cs.push(me); init(me); share(); })
}/*usage: sys.trigger('join',me)*/
;

システムに自分自身を知らせる。これによりchange changedをデータストアが管理できる。

sys.trigger('join',riot.mount('res',{})[0])

全部

edとresはお互いを知らないがデータ変更されたことは第三者から通知される。

<script src="//gnjo.github.io/riot.js"></script>
<div><ed></ed></div>
<div><res></res></div>
<style> div{border-bottom:1px solid}</style>
var sys=new function(){
 riot.observable(this); 
 let self=this,cs=[],share=()=>{ cs.filter(d=>d).map(d=>d.trigger('changed',self.store))}
 //cs.filter mean fall the child.
 ,init =(d)=>{d.on('change',(o)=>{ Object.assign(self.store,o); share() })} 
 self.store={}
 self.on('join',(me)=>{ cs.push(me); init(me); share(); })
}/*usage: sys.trigger('join',me)*/
;
riot.tag('ed','<div ref="code" contenteditable="plaintext-only" oninput="{input}"></div>',function(opts){
 let self=this,code=null;
 self.on('mount',()=>{code=self.refs.code})
 self.on('changed',(d)=>{ if(code.textContent!=d.ed) code.textContent=d.ed })
 self.input=()=>{ self.trigger('change',{ed:code.textContent}) }
})
sys.trigger('join',riot.mount('ed',{})[0])
;
riot.tag('res','<label>{result}</label>',function(opts){
 let self=this;
 self.result=0;
 self.on('changed',(d)=>{ if(d.ed) self.result = d.ed.length||0; self.update(); })
})
sys.trigger('join',riot.mount('res',{})[0])
;
2
1
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
2
1