最近,@ sanReal上的一篇文章发表在Habr上,亚历山大在这里谈论了他从自己的经验中学到的Svelte的技术和功能。令我惊讶的是,在他的清单中没有提到最强大的框架工具之一-Actions。另外,通过与@sveltejs社区中已经在使用Svelte创建非常好的应用程序的人们进行交流,我有时会注意到并不是每个人都使用Actions,即使他们的应用程序可以理想地解决问题。在本文中,我将告诉您什么是动作,并通过最简单的示例来说明它们的应用。

假设我们有一个文本框,用户必须在其中输入电话号码。我们需要确保用户只能在该字段中输入数字。
: +7 <input type="text" />
当任务是为标准HTML元素赋予附加功能时,在框架的任何组件中工作以围绕该元素创建可重用组件的做法是常见的做法,在该组件内部实施非标准行为的逻辑。您可以在Svelte中执行相同的操作:
<script>
function clean_value(e){
e.target.value = e.target.value.replace(/[^\d]/g,'');
}
</script>
<input type="text" on:input={clean_value} />
...
: +7 <InputDigits />
观看中
任务已经完成,但是元素本身<input/>
现在隐藏在组件内部,因此我们将无法再将其作为常规HTML元素进行操作-要在其上“挂起”任何CSS类,事件处理程序或某些特殊属性,将变得不那么简单。
Svelte — ( Actions). Svelte , , , , — "" , . — - HTML-. , DOM. DOM-, .
:
<script>
function onlydigits(node) {
function clean_value(){
node.value = node.value.replace(/[^\d]/g,'');
}
node.addEventListener('input',clean_value);
return {
destroy: ()=>node.removeEventListener('input',clean_value)
}
}
</script>
: +7 <input type="text" use:onlydigits />
onlydigits
, . , DOM- node
input
. , destroy
, DOM-, .
Svelte, - HTML- , use
. <input/>
use:onlydigits
.
. , 10 :
<script>
function onlydigits(node) { ... }
function max10symbols(node) {
function trim_value(){
node.value = node.value.substring(0, 10);
}
node.addEventListener('input',trim_value);
return {
destroy: ()=>node.removeEventListener('input',trim_value)
}
}
</script>
: +7 <input type="text" use:onlydigits use:max10symbols />
<input />
— use:onlydigits
use:max10symbols
. .
use
, . , . :
<script>
function format_by_pattern(node,pattern) {
function set_cursor(){
const match = node.value.match(/[\d]/gi);
const pos = match ? node.value.lastIndexOf(match.pop())+1 : 0;
node.setSelectionRange(pos, pos);
}
function format_value(e){
let digits = node.value.replace(/[^\d]/g,'').split('');
node.value = pattern.replace(/[*]/g,(m)=>digits.shift()||m);
set_cursor();
}
node.addEventListener('input',format_value);
format_value();
return {
destroy: ()=>node.removeEventListener('input',format_value)
}
}
</script>
: +7 <input type="text" use:format_by_pattern={'(***) ***-**-**'} /> <br/>
: <input type="text" use:format_by_pattern={' **** №******'} />
<input />
HTML-. format_by_pattern
, . , Svelte, JavaScript-.
, , , . .
<script>
function format_by_pattern(node,pattern) {
function set_cursor(){...}
function format_value(){...}
...
return {
destroy: ...,
update: (new_pattern)=>{
pattern=new_pattern;
format_value();
}
}
}
let zagran = false;
</script>
: +7 <input type="text" use:format_by_pattern={'(***) ***-**-**'} /> <br/>
: <input type="text" use:format_by_pattern={zagran ? ' ** №*******' : ' **** №******'} /> <br/>
<input type="checkbox" bind:checked={zagran}/> -
, . , , bind:checked
, zagran
true
false
. , Svelte use:format_by_pattern
.
, , DOM-, <input />
DOM-, . .
, , , — update
. , . .
. , . , , DOM- — , . Svelte. Svelte , , .
注意:很快将在莫斯科举行Svelte Russia Meetup#1。注册,还有空间。对于那些无法亲自参加的人,将组织该活动的广播和录制。