index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function nbInit($s){
  2. function nBind(callback){
  3. for (var selector in $s){
  4. var items = document.querySelectorAll(selector);
  5. items = items.length ? items : document.querySelectorAll("#" + selector);
  6. for (var i=0,item=items[i];i<items.length;i++,item=items[i]){
  7. callback(item, $s, selector)
  8. }
  9. }
  10. }
  11. function syncToDOM(){
  12. nBind(function(item, $s, selector){
  13. if (item.type === 'radio'){
  14. if (item.value === $s[selector]){
  15. item.checked = true;
  16. }
  17. return;
  18. }
  19. if (item.type === 'checkbox'){
  20. item.checked = !!$s[selector];
  21. return;
  22. }
  23. item["value" in item ? "value" : "innerText"] = $s[selector];
  24. });
  25. }
  26. function syncFromDOM(){
  27. nBind(function(item, $s, selector){
  28. if (item.type === 'radio'){
  29. if (item.checked)
  30. $s[selector] = item.value;
  31. return;
  32. }
  33. if (item.type === 'checkbox'){
  34. $s[selector] = item.checked;
  35. return;
  36. }
  37. $s[selector] = item["value" in item ? "value" : "innerText"];
  38. });
  39. }
  40. syncToDOM();
  41. var scopeProxy = new Proxy($s,{
  42. get(target, prop){
  43. if (!(prop in target) && (document.querySelectorAll(prop).length || document.querySelectorAll("#" +prop).length)){
  44. target[prop] = null;
  45. }
  46. syncFromDOM();
  47. return target[prop];
  48. },
  49. set(target, prop, value){
  50. syncFromDOM();
  51. target[prop] = value
  52. syncToDOM();
  53. return true;
  54. },
  55. })
  56. return scopeProxy;
  57. }
  58. var $s = nbInit({
  59. text1: "txt",
  60. p1: "para"
  61. });