123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- function nbInit($s){
- function nBind(callback){
- for (var selector in $s){
- var items = document.querySelectorAll(selector);
- items = items.length ? items : document.querySelectorAll("#" + selector);
- for (var i=0,item=items[i];i<items.length;i++,item=items[i]){
- callback(item, $s, selector)
- }
- }
- }
- function syncToDOM(){
- nBind(function(item, $s, selector){
- if (item.type === 'radio'){
- if (item.value === $s[selector]){
- item.checked = true;
- }
- return;
- }
- if (item.type === 'checkbox'){
- item.checked = !!$s[selector];
- return;
- }
- item["value" in item ? "value" : "innerText"] = $s[selector];
- });
- }
- function syncFromDOM(){
- nBind(function(item, $s, selector){
- if (item.type === 'radio'){
- if (item.checked)
- $s[selector] = item.value;
- return;
- }
- if (item.type === 'checkbox'){
- $s[selector] = item.checked;
- return;
- }
- $s[selector] = item["value" in item ? "value" : "innerText"];
- });
- }
- syncToDOM();
- var scopeProxy = new Proxy($s,{
- get(target, prop){
- if (!(prop in target) && (document.querySelectorAll(prop).length || document.querySelectorAll("#" +prop).length)){
- target[prop] = null;
- }
- syncFromDOM();
- return target[prop];
- },
- set(target, prop, value){
- syncFromDOM();
- target[prop] = value
- syncToDOM();
- return true;
- },
- })
- return scopeProxy;
- }
- var $s = nbInit({
- text1: "txt",
- p1: "para"
- });
|