Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

布尔属性的设计 #102

Open
xinglie opened this issue Jun 15, 2022 · 1 comment
Open

布尔属性的设计 #102

xinglie opened this issue Jun 15, 2022 · 1 comment

Comments

@xinglie
Copy link
Owner

xinglie commented Jun 15, 2022

HTML规范

对于一个布尔属性,如果节点存该属性key,则表示为true,否则为false,当存在属性时key时,无视value是什么值。如下inputchecked属性

<input type="checkbox" checked /><!--表示选中-->
<input type="checkbox" checked="checked" /><!--旧规范需要的选中-->
<input type="checkbox" checked="" /><!--依然选中-->
<input type="checkbox" checked="false" /><!--还是选中-->
<input type="checkbox" checked="0" /><!--同样是选中-->

我们会发现节点的布尔属性只要存在即为true,尽管它的valuejavascript中的falsy值。这是因为htmljavascript是两回事,不能拿javascript中的falsy值在html中使用。

HTML的扩展

诚然,对于html来讲,有它自己的规范考量。我们在使用时,多少会有些不方便,比如用innerHTML渲染一段html片断时,我们只能根据条件来输出是否有checked这样的布尔属性来表达相应的界面,比如

body.innerHTML=`<input type="checkbox" ${checked?'checked':''} />`

这多少有点不方便,如果html中的属性本身就支持根据trusyfalsy的值来表达相应的界面该多好?

虚拟DOM的扩展

react为代表的使用虚拟dom的框架如何处理该问题?

<input type="checkbox" checked={checked} />

此为扩展了html属性value的处理,当属性值为falsy时,删除相应的属性

片断解析

fast为代表的解析引擎则扩展了属性keyhttps://www.fast.design/docs/fast-element/declaring-templates

<button type="submit" ?disabled="${x => !x.enabled}">Submit</button>

我们可以看到disabled变成发?disabled,明确告诉解析引擎这是一个需要特殊处理的布尔属性

magix5中的布尔属性

magix5采用的是html属性value的处理,当属性valuefalsy时,删除相应的属性

magix5前期在处理时,虽然采用的是value的处理,但是增加了语法,如<input type="checkbox" checked="{{=checked}}?"/>来表达当checked值为trusy时,保留checked属性,否则就删除。这样的写法有学习成本,好处是方便扩展其它语法,如非空语法,我们可以写成<input type="checkbox" checked="{{=checked}}??"/>来表达当checkednullundefined时,则删除checked属性。

考虑到使用场景和学习成本,以上语法仅保留,不再作为主推写法,目前直接写<input type="checkbox" checked="{{=checked}}"/>即可。至于非空语法,根据实际场景的应用,大概率也是使用不到的,功能保留,不作主要语法介绍。

当然,对于<mx-vframe src="./view" *params="{{=params}}??"/>,向子view传递参数时,属性也支持这样的写法

至于*params="{{=params}}??"*params="{{=params}}"的区别,前者当paramsnullundefined时,传递到子view中的参数是不包含params这个key的,后者会包含。考虑到具体使用及差异,这个语法就暂时保留吧,不是主要功能。

@xinglie
Copy link
Owner Author

xinglie commented Jun 15, 2022

#100

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant