From 9e6b175519dbcc78303d7315ffb08c6a53488156 Mon Sep 17 00:00:00 2001 From: Ilya Sarantsev Date: Mon, 21 Aug 2017 18:55:42 +0300 Subject: [PATCH] Handle shared attributes object in hyperscript (#1941) --- docs/change-log.md | 1 + render/hyperscript.js | 12 ++++++++++++ render/tests/test-hyperscript.js | 17 +++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/docs/change-log.md b/docs/change-log.md index 82686f0e..e73ff1b6 100644 --- a/docs/change-log.md +++ b/docs/change-log.md @@ -36,6 +36,7 @@ #### Bug fixes: - core: don't call `onremove` on the children of components that return null from the view [#1921](https://github.com/MithrilJS/mithril.js/issues/1921) [octavore](https://github.com/octavore) ([#1922](https://github.com/MithrilJS/mithril.js/pull/1922)) +- hypertext: correct handling of shared attributes object passed to `m()`. Will copy attributes when it's necessary [#1941](https://github.com/MithrilJS/mithril.js/issues/1941) [s-ilya](https://github.com/s-ilya) ([#1942](https://github.com/MithrilJS/mithril.js/pull/1942)) --- diff --git a/render/hyperscript.js b/render/hyperscript.js index 5b5fda29..ea56c893 100644 --- a/render/hyperscript.js +++ b/render/hyperscript.js @@ -28,6 +28,18 @@ function execSelector(state, attrs, children) { var hasAttrs = false, childList, text var className = attrs.className || attrs.class + if (Object.keys(state.attrs).length && Object.keys(attrs).length) { + var newAttrs = {} + + for(var key in attrs) { + if (hasOwn.call(attrs, key)) { + newAttrs[key] = attrs[key] + } + } + + attrs = newAttrs + } + for (var key in state.attrs) { if (hasOwn.call(state.attrs, key)) { attrs[key] = state.attrs[key] diff --git a/render/tests/test-hyperscript.js b/render/tests/test-hyperscript.js index 498a9dbf..f7c5f889 100644 --- a/render/tests/test-hyperscript.js +++ b/render/tests/test-hyperscript.js @@ -507,6 +507,23 @@ o.spec("hyperscript", function() { o(vnode.children[0].tag).equals("i") o(vnode.children[1].tag).equals("s") }) + o("handles shared attrs", function() { + var attrs = {a: "b"} + + var nodeA = m(".a", attrs) + var nodeB = m(".b", attrs) + + o(nodeA.attrs.className).equals("a") + o(nodeA.attrs.a).equals("b") + + o(nodeB.attrs.className).equals("b") + o(nodeB.attrs.a).equals("b") + }) + o("doesnt modify passed attributes object", function() { + var attrs = {a: "b"} + m(".a", attrs) + o(attrs).deepEquals({a: "b"}) + }) o("handles fragment children without attr unwrapped", function() { var vnode = m("div", [m("i")], [m("s")])