Created
August 11, 2018 04:29
-
-
Save kasuganosora/ce6ca742378ff9cf1e03e7efcde91995 to your computer and use it in GitHub Desktop.
JS 变量绑定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var testData = { | |
"a.b.c": 9, | |
gs: [3,1,23], | |
nest: { | |
a:233, | |
"b.c": 911, | |
b:{ | |
g: 254, | |
c: 623 | |
} | |
} | |
} | |
function bindObjeChangeEvent(obj, propertyName, getter = null, setter = null){ | |
if(!getter && !setter){ | |
return; | |
} | |
if(obj.hasOwnProperty(propertyName)){ | |
var val = obj[propertyName]; | |
if(typeof val == "object" && !Array.isArray(val)){ | |
return; | |
} | |
if(!obj.hasOwnProperty("_store")){ | |
var store = {}; | |
Object.defineProperty(obj, "_store", { | |
"enumerable": false, | |
"configurable": false, | |
get: function(){ return store; }, | |
}); | |
} | |
obj._store[propertyName] = obj[propertyName]; | |
Object.defineProperty(obj, propertyName, { | |
enumerable: true, | |
configurable: true, | |
get: function(){ | |
if(typeof getter == "function"){ | |
return getter(obj, obj._store[propertyName]); | |
} | |
return val; | |
}, | |
set: function(newVal){ | |
if(typeof setter == "function" && val != newVal){ | |
setter(obj, propertyName, newVal) | |
} | |
} | |
}); | |
return; | |
} | |
let pathList= propertyName.split("."); | |
let currObj = obj[pathList.shift()]; | |
if(pathList.length == 0){ | |
return; | |
} | |
return bindObjeChangeEvent(currObj, pathList.join("."), getter, setter); | |
} | |
bindObjeChangeEvent(testData, "nest.b.c", function(obj, val){ | |
console.log("你读取我干啥呢"); | |
return val; | |
}, function(obj, propertyName, newVal){ | |
var oldVal = obj._store[propertyName]; | |
console.log("你改我干什么呢 " + oldVal + " -> " + newVal); | |
obj._store[propertyName] = newVal; | |
}); | |
bindObjeChangeEvent(testData, "nest", function(obj, val){ | |
console.log("nest 你读取我干啥呢"); | |
return val; | |
}, function(obj, propertyName, newVal){ | |
var oldVal = obj._store[propertyName]; | |
console.log("nest 你改我干什么呢 " + oldVal + " -> " + newVal); | |
obj._store[propertyName] = newVal; | |
}); | |
console.log(testData.nest["b.c"]); | |
testData.nest["b.c"] = 233; | |
console.log(testData.nest["b.c"]); | |
function getSetPath(obj, propertyName, value = undefined){ | |
if(obj.hasOwnProperty(propertyName)){ | |
if(value !== undefined){ | |
obj[propertyName] = value; | |
} | |
return obj[propertyName]; | |
} | |
let pathList= propertyName.split("."); | |
let currObj = obj[pathList.shift()]; | |
if(pathList.length == 0){ | |
return null; | |
} | |
return getSetPath(currObj, pathList.join("."), value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment