From 32c71f105bd5e503a335a67c4ca1c8cbb810f3f5 Mon Sep 17 00:00:00 2001 From: Kevin Batdorf Date: Fri, 25 Sep 2020 12:37:37 +0700 Subject: [PATCH] Add support for deep prop updating on $parent/$component (#14) --- dist/component.js | 2 +- dist/index.js | 2 +- example/component.html | 22 ++++++++++++++++++++-- src/component.js | 41 +++++++++++++++++++++++++++++++++-------- 4 files changed, 55 insertions(+), 12 deletions(-) diff --git a/dist/component.js b/dist/component.js index 0c04318..1d6182d 100644 --- a/dist/component.js +++ b/dist/component.js @@ -1 +1 @@ -!function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/",r(r.s=33)}({10:function(t,e,r){"use strict";function n(t){return function(t){if(Array.isArray(t))return o(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r2&&void 0!==arguments[2]?arguments[2]:{};return"function"==typeof t?t.call(e):new Function(["$data"].concat(n(Object.keys(r))),"var __alpine_result; with($data) { __alpine_result = ".concat(t," }; return __alpine_result")).apply(void 0,[e].concat(n(Object.values(r))))}Alpine.magicProperties.hasOwnProperty("parent")||Alpine.addMagicProperty("parent",(function(r){if(void 0!==r.$parent)return r.$parent;var n,o=r.parentNode.closest("[x-data]");if(!o)throw"Parent component not found";return o.setAttribute("x-bind:data-last-refresh","Date.now()"),n=o.__x?o.__x.getUnobservedData():e(o.getAttribute("x-data"),o),r.$parent=t(n,o),new MutationObserver((function(e){for(var n=0;nt.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&void 0!==arguments[0]?arguments[0]:null;return{get:function(e,r){if(null!=typeof e[r]&&"object"===a(e[r])){var o=n?"".concat(n,".").concat(r):r;return new Proxy(e[r],t(o))}return e[r]},set:function(t,o,a){if(!e.__x)throw"Error communicating with observed component";var i=n?"".concat(n,".").concat(o):o;return r(e.__x.$data,i,a),!0}}}())}function e(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return"function"==typeof t?t.call(e):new Function(["$data"].concat(n(Object.keys(r))),"var __alpine_result; with($data) { __alpine_result = ".concat(t," }; return __alpine_result")).apply(void 0,[e].concat(n(Object.values(r))))}function r(t,e,r){return(e=e.toString().match(/[^.[\]]+/g)||[]).slice(0,-1).reduce((function(t,r,n){return Object(t[r])===t[r]?t[r]:t[r]=Math.abs(e[n+1])>>0==+e[n+1]?[]:{}}),t)[e[e.length-1]]=r,t}Alpine.magicProperties.hasOwnProperty("parent")||Alpine.addMagicProperty("parent",(function(r){if(void 0!==r.$parent)return r.$parent;var n,o=r.parentNode.closest("[x-data]");if(!o)throw"Parent component not found";return o.setAttribute("x-bind:data-last-refresh","Date.now()"),n=o.__x?o.__x.getUnobservedData():e(o.getAttribute("x-data"),o),r.$parent=t(n,o),new MutationObserver((function(e){for(var n=0;n=200&&e<300}};s.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],(function(e){s.headers[e]={}})),n.forEach(["post","put","patch"],(function(e){s.headers[e]=n.merge(i)})),e.exports=s}).call(this,r(19))},function(e,t,r){"use strict";var n=r(0),o=r(21),i=r(3),a=r(23),u=r(26),s=r(27),c=r(7);e.exports=function(e){return new Promise((function(t,f){var l=e.data,p=e.headers;n.isFormData(l)&&delete p["Content-Type"];var d=new XMLHttpRequest;if(e.auth){var h=e.auth.username||"",m=e.auth.password||"";p.Authorization="Basic "+btoa(h+":"+m)}var y=a(e.baseURL,e.url);if(d.open(e.method.toUpperCase(),i(y,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d.onreadystatechange=function(){if(d&&4===d.readyState&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var r="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,n={data:e.responseType&&"text"!==e.responseType?d.response:d.responseText,status:d.status,statusText:d.statusText,headers:r,config:e,request:d};o(t,f,n),d=null}},d.onabort=function(){d&&(f(c("Request aborted",e,"ECONNABORTED",d)),d=null)},d.onerror=function(){f(c("Network Error",e,null,d)),d=null},d.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),f(c(t,e,"ECONNABORTED",d)),d=null},n.isStandardBrowserEnv()){var v=r(28),g=(e.withCredentials||s(y))&&e.xsrfCookieName?v.read(e.xsrfCookieName):void 0;g&&(p[e.xsrfHeaderName]=g)}if("setRequestHeader"in d&&n.forEach(p,(function(e,t){void 0===l&&"content-type"===t.toLowerCase()?delete p[t]:d.setRequestHeader(t,e)})),n.isUndefined(e.withCredentials)||(d.withCredentials=!!e.withCredentials),e.responseType)try{d.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){d&&(d.abort(),f(e),d=null)})),void 0===l&&(l=null),d.send(l)}))}},function(e,t,r){"use strict";var n=r(22);e.exports=function(e,t,r,o,i){var a=new Error(e);return n(a,t,r,o,i)}},function(e,t,r){"use strict";var n=r(0);e.exports=function(e,t){t=t||{};var r={},o=["url","method","params","data"],i=["headers","auth","proxy"],a=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];n.forEach(o,(function(e){void 0!==t[e]&&(r[e]=t[e])})),n.forEach(i,(function(o){n.isObject(t[o])?r[o]=n.deepMerge(e[o],t[o]):void 0!==t[o]?r[o]=t[o]:n.isObject(e[o])?r[o]=n.deepMerge(e[o]):void 0!==e[o]&&(r[o]=e[o])})),n.forEach(a,(function(n){void 0!==t[n]?r[n]=t[n]:void 0!==e[n]&&(r[n]=e[n])}));var u=o.concat(i).concat(a),s=Object.keys(t).filter((function(e){return-1===u.indexOf(e)}));return n.forEach(s,(function(n){void 0!==t[n]?r[n]=t[n]:void 0!==e[n]&&(r[n]=e[n])})),r}},function(e,t,r){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,r){"use strict";function n(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r2&&void 0!==arguments[2]?arguments[2]:{};return"function"==typeof e?e.call(t):new Function(["$data"].concat(n(Object.keys(r))),"var __alpine_result; with($data) { __alpine_result = ".concat(e," }; return __alpine_result")).apply(void 0,[t].concat(n(Object.values(r))))}Alpine.magicProperties.hasOwnProperty("parent")||Alpine.addMagicProperty("parent",(function(r){if(void 0!==r.$parent)return r.$parent;var n,o=r.parentNode.closest("[x-data]");if(!o)throw"Parent component not found";return o.setAttribute("x-bind:data-last-refresh","Date.now()"),n=o.__x?o.__x.getUnobservedData():t(o.getAttribute("x-data"),o),r.$parent=e(n,o),new MutationObserver((function(t){for(var n=0;n1)for(var r=1;r=0)return;a[t]="set-cookie"===t?(a[t]?a[t]:[]).concat([r]):a[t]?a[t]+", "+r:r}})),a):a}},function(e,t,r){"use strict";var n=r(0);e.exports=n.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function o(e){var n=e;return t&&(r.setAttribute("href",n),n=r.href),r.setAttribute("href",n),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=o(window.location.href),function(t){var r=n.isString(t)?o(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0}},function(e,t,r){"use strict";var n=r(0);e.exports=n.isStandardBrowserEnv()?{write:function(e,t,r,o,i,a){var u=[];u.push(e+"="+encodeURIComponent(t)),n.isNumber(r)&&u.push("expires="+new Date(r).toGMTString()),n.isString(o)&&u.push("path="+o),n.isString(i)&&u.push("domain="+i),!0===a&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(e,t,r){"use strict";var n=r(9);function o(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new n(e),t(r.reason))}))}o.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},o.source=function(){var e;return{token:new o((function(t){e=t})),cancel:e}},e.exports=o},function(e,t,r){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,r){e.exports=r(32)},function(e,t,r){"use strict";r.r(t);var n=r(10),o=r(11),i=r(12),a=r.n(i),u=r(13),s=r.n(u),c=window.deferLoadingAlpine||function(e){return e()};window.deferLoadingAlpine=function(e){Object(n.default)(),Object(o.default)(),a()(),s()(),c(e)},t.default={registerComponentMagicMethod:n.default,registerFetchMagicMethod:o.default,registerIntervalMagicMethod:a.a,registerTruncateMagicMethod:s.a}}]); \ No newline at end of file +!function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)n.d(r,o,function(e){return t[e]}.bind(null,o));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="/",n(n.s=31)}([function(t,e,n){"use strict";var r=n(2),o=Object.prototype.toString;function i(t){return"[object Array]"===o.call(t)}function a(t){return void 0===t}function u(t){return null!==t&&"object"==typeof t}function s(t){return"[object Function]"===o.call(t)}function c(t,e){if(null!=t)if("object"!=typeof t&&(t=[t]),i(t))for(var n=0,r=t.length;n=200&&t<300}};s.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],(function(t){s.headers[t]={}})),r.forEach(["post","put","patch"],(function(t){s.headers[t]=r.merge(i)})),t.exports=s}).call(this,n(19))},function(t,e,n){"use strict";var r=n(0),o=n(21),i=n(3),a=n(23),u=n(26),s=n(27),c=n(7);t.exports=function(t){return new Promise((function(e,f){var l=t.data,p=t.headers;r.isFormData(l)&&delete p["Content-Type"];var d=new XMLHttpRequest;if(t.auth){var h=t.auth.username||"",m=t.auth.password||"";p.Authorization="Basic "+btoa(h+":"+m)}var y=a(t.baseURL,t.url);if(d.open(t.method.toUpperCase(),i(y,t.params,t.paramsSerializer),!0),d.timeout=t.timeout,d.onreadystatechange=function(){if(d&&4===d.readyState&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,r={data:t.responseType&&"text"!==t.responseType?d.response:d.responseText,status:d.status,statusText:d.statusText,headers:n,config:t,request:d};o(e,f,r),d=null}},d.onabort=function(){d&&(f(c("Request aborted",t,"ECONNABORTED",d)),d=null)},d.onerror=function(){f(c("Network Error",t,null,d)),d=null},d.ontimeout=function(){var e="timeout of "+t.timeout+"ms exceeded";t.timeoutErrorMessage&&(e=t.timeoutErrorMessage),f(c(e,t,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var v=n(28),g=(t.withCredentials||s(y))&&t.xsrfCookieName?v.read(t.xsrfCookieName):void 0;g&&(p[t.xsrfHeaderName]=g)}if("setRequestHeader"in d&&r.forEach(p,(function(t,e){void 0===l&&"content-type"===e.toLowerCase()?delete p[e]:d.setRequestHeader(e,t)})),r.isUndefined(t.withCredentials)||(d.withCredentials=!!t.withCredentials),t.responseType)try{d.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&d.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then((function(t){d&&(d.abort(),f(t),d=null)})),void 0===l&&(l=null),d.send(l)}))}},function(t,e,n){"use strict";var r=n(22);t.exports=function(t,e,n,o,i){var a=new Error(t);return r(a,e,n,o,i)}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e){e=e||{};var n={},o=["url","method","params","data"],i=["headers","auth","proxy"],a=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];r.forEach(o,(function(t){void 0!==e[t]&&(n[t]=e[t])})),r.forEach(i,(function(o){r.isObject(e[o])?n[o]=r.deepMerge(t[o],e[o]):void 0!==e[o]?n[o]=e[o]:r.isObject(t[o])?n[o]=r.deepMerge(t[o]):void 0!==t[o]&&(n[o]=t[o])})),r.forEach(a,(function(r){void 0!==e[r]?n[r]=e[r]:void 0!==t[r]&&(n[r]=t[r])}));var u=o.concat(i).concat(a),s=Object.keys(e).filter((function(t){return-1===u.indexOf(t)}));return r.forEach(s,(function(r){void 0!==e[r]?n[r]=e[r]:void 0!==t[r]&&(n[r]=t[r])})),n}},function(t,e,n){"use strict";function r(t){this.message=t}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,t.exports=r},function(t,e,n){"use strict";function r(t){return function(t){if(Array.isArray(t))return o(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return o(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);"Object"===n&&t.constructor&&(n=t.constructor.name);if("Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return o(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n0&&void 0!==arguments[0]?arguments[0]:null;return{get:function(e,n){if(null!=typeof e[n]&&"object"===i(e[n])){var o=r?"".concat(r,".").concat(n):n;return new Proxy(e[n],t(o))}return e[n]},set:function(t,o,i){if(!e.__x)throw"Error communicating with observed component";var a=r?"".concat(r,".").concat(o):o;return n(e.__x.$data,a,i),!0}}}())}function e(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return"function"==typeof t?t.call(e):new Function(["$data"].concat(r(Object.keys(n))),"var __alpine_result; with($data) { __alpine_result = ".concat(t," }; return __alpine_result")).apply(void 0,[e].concat(r(Object.values(n))))}function n(t,e,n){return(e=e.toString().match(/[^.[\]]+/g)||[]).slice(0,-1).reduce((function(t,n,r){return Object(t[n])===t[n]?t[n]:t[n]=Math.abs(e[r+1])>>0==+e[r+1]?[]:{}}),t)[e[e.length-1]]=n,t}Alpine.magicProperties.hasOwnProperty("parent")||Alpine.addMagicProperty("parent",(function(n){if(void 0!==n.$parent)return n.$parent;var r,o=n.parentNode.closest("[x-data]");if(!o)throw"Parent component not found";return o.setAttribute("x-bind:data-last-refresh","Date.now()"),r=o.__x?o.__x.getUnobservedData():e(o.getAttribute("x-data"),o),n.$parent=t(r,o),new MutationObserver((function(e){for(var r=0;r1)for(var n=1;n=0)return;a[e]="set-cookie"===e?(a[e]?a[e]:[]).concat([n]):a[e]?a[e]+", "+n:n}})),a):a}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){var t,e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function o(t){var r=t;return e&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=o(window.location.href),function(e){var n=r.isString(e)?o(e):e;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?{write:function(t,e,n,o,i,a){var u=[];u.push(t+"="+encodeURIComponent(e)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),!0===a&&u.push("secure"),document.cookie=u.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(t,e,n){"use strict";var r=n(9);function o(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise((function(t){e=t}));var n=this;t((function(t){n.reason||(n.reason=new r(t),e(n.reason))}))}o.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},o.source=function(){var t;return{token:new o((function(e){t=e})),cancel:t}},t.exports=o},function(t,e,n){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,n){t.exports=n(32)},function(t,e,n){"use strict";n.r(e);var r=n(10),o=n(11),i=n(12),a=n.n(i),u=n(13),s=n.n(u),c=window.deferLoadingAlpine||function(t){return t()};window.deferLoadingAlpine=function(t){Object(r.default)(),Object(o.default)(),a()(),s()(),c(t)},e.default={registerComponentMagicMethod:r.default,registerFetchMagicMethod:o.default,registerIntervalMagicMethod:a.a,registerTruncateMagicMethod:s.a}}]); \ No newline at end of file diff --git a/example/component.html b/example/component.html index 3d81676..a1bda7d 100644 --- a/example/component.html +++ b/example/component.html @@ -43,11 +43,12 @@

Watch a parent component and external component that does not have a visible mutation

+

NB: Color should remain teal since no mutation

+ @click="color = color === 'foo' ? 'bar' : 'foo'">

@@ -61,5 +62,22 @@

press here

+

Updating nested property (`$parent.square.color`)

+
+

press here

+
+

Updating deeper nested property (`$parent.shape.square.color`)

+
+

press here

+
+ + diff --git a/src/component.js b/src/component.js index b055b1c..ad43c33 100644 --- a/src/component.js +++ b/src/component.js @@ -78,16 +78,26 @@ function registerComponentMagicMethod() { } }) function allowTwoWayCommunication(data, observedComponent) { - return new Proxy(data, { - set(object, prop, value) { - if (!observedComponent.__x) { - throw 'Error communicating with observed component' + const handler = (scope = null) => { + return { + get(target, key) { + if (typeof target[key] != null && typeof target[key] === 'object') { + const path = scope ? `${scope}.${key}` : key + return new Proxy(target[key], handler(path)) + } + return target[key] + }, + set(target, key, value) { + if (!observedComponent.__x) { + throw 'Error communicating with observed component' + } + const path = scope ? `${scope}.${key}` : key + objectSetDeep(observedComponent.__x.$data, path, value) + return true } - observedComponent.__x.$data[prop] = value - observedComponent.__x.updateElements(observedComponent) - return true } - }) + } + return new Proxy(data, handler()) } // This was taken from AlpineJs unaltered @@ -99,6 +109,21 @@ function registerComponentMagicMethod() { dataContext, ...Object.values(additionalHelperVariables) ) } + + // Borrowed from https://stackoverflow.com/a/54733755/1437789 + function objectSetDeep (object, path, value) { + path = path.toString().match(/[^.[\]]+/g) || []; + path.slice(0, -1).reduce((a, currentKey, index) => // Iterate all of them except the last one + Object(a[currentKey]) === a[currentKey] // Does the key exist and is its value an object? + // Yes: then follow that path + ? a[currentKey] + // No: create the key. Is the next key a potential array-index? + : a[currentKey] = Math.abs(path[index + 1]) >> 0 === +path[index + 1] + ? [] // Yes: assign a new array object + : {}, // No: assign a new plain object + object)[path[path.length - 1]] = value // Finally assign the value to the last key + return object + } } const alpine = window.deferLoadingAlpine || ((alpine) => alpine())