proxy数据代理
let inp = document. getElementById ( 'inp' )
let oDiv = document. getElementById ( 'box' )
let elems = [ inp, oDiv]
let obj = {
value: '这是obj的初始值'
}
function initVal ( obj) {
if ( typeof obj!= 'object' ) throw new Error ( 'obj is not object' )
for ( let i= 0 ; i< elems. length; i++ ) {
let elem = elems[ i]
let attrs = elem. attributes
for ( let i= 0 ; i< attrs. length; i++ ) {
if ( attrs[ i] . nodeName. indexOf ( 'data' ) > - 1 ) {
let prop = attrs[ i] . nodeName. slice ( 5 )
prop = prop == 'innerhtml' ? 'innerHTML' : prop
let propVal = attrs[ i] . nodeValue
elem[ prop] = obj[ propVal]
}
}
}
}
initVal ( obj)
let proxy = new Proxy ( obj, {
get ( target, p, receiver) {
return target[ p]
} ,
set ( target, p, value, receiver) {
target[ p] = value
initVal ( target)
}
} )
inp. addEventListener ( 'input' , function ( ) {
proxy. value = this . value
} )
Object.defineproperty()劫持数据
< script>
let obj = { msg: 'hello world' }
function getEleById ( id) {
return document. getElementById ( id)
}
let inp = getEleById ( 'inp' )
let p = getEleById ( 'p' )
let elems = [ inp, p]
function initVal ( obj) {
elems. forEach ( function ( item, index) {
let attrs = item. attributes
for ( let i = 0 , len = attrs. length; i < len; i++ ) {
if ( attrs[ i] . nodeName. indexOf ( 'data' ) > - 1 ) {
let prop = attrs[ i] . nodeName. slice ( 5 )
prop = prop == 'innerhtml' ? 'innerHTML' : prop
let propVal = attrs[ i] . nodeValue
item[ prop] = obj[ propVal]
console. log ( propVal)
console. log ( prop)
console. log ( attrs[ i] )
}
}
} )
}
initVal ( obj)
let newObj = { }
Object. defineProperty ( newObj, 'msg' , {
get ( ) {
return obj. msg
} ,
set ( val) {
obj. msg = val;
initVal ( obj)
}
} )
inp. addEventListener ( 'input' , function ( ) {
newObj. msg = this . value
console. log ( 123 )
} )
< / script>