1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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"
- });
- document.onchange = function(){
- $s.state = "";
- $s.state = JSON.stringify($s, null, 4);
- }
|