From bf7d73215547b75ace9294b029c0cbf2317f29d1 Mon Sep 17 00:00:00 2001 From: shibao Date: Sun, 23 Jan 2022 00:02:08 -0500 Subject: [PATCH] add maintain attrs hook --- assets/js/app.js | 6 +++++- assets/js/maintain_attrs.js | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 assets/js/maintain_attrs.js diff --git a/assets/js/app.js b/assets/js/app.js index 85814181..cbc68575 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -25,9 +25,13 @@ import "phoenix_html" import {Socket} from "phoenix" import {LiveSocket} from "phoenix_live_view" import topbar from "../vendor/topbar" +import MaintainAttrs from './maintain_attrs' let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") -let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) +let liveSocket = new LiveSocket("/live", Socket, { + params: { _csrf_token: csrfToken }, + hooks: { MaintainAttrs } +}) // Show progress bar on live navigation and form submits topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) diff --git a/assets/js/maintain_attrs.js b/assets/js/maintain_attrs.js new file mode 100644 index 00000000..68ba6d1d --- /dev/null +++ b/assets/js/maintain_attrs.js @@ -0,0 +1,8 @@ +// maintain user adjusted attributes, like textbox length on phoenix liveview +// update. https://github.com/phoenixframework/phoenix_live_view/issues/1011 + +export default { + attrs(){ return this.el.getAttribute("data-attrs").split(", ") }, + beforeUpdate(){ this.prevAttrs = this.attrs().map(name => [name, this.el.getAttribute(name)]) }, + updated(){ this.prevAttrs.forEach(([name, val]) => this.el.setAttribute(name, val)) } +}