Update common

master
yutent 2023-09-22 17:56:51 +08:00
parent d796b5f6a2
commit 30685927d4
1 changed files with 156 additions and 1 deletions

157
common.md

@ -1 +1,156 @@
Welcome to the Wiki.
# 常用方法
> 除了几大模块之外, 框架内部还集成了几个常用方法。
### $(selector`<String>`, container`<Dom>`)
> 原生`querySelector()`的简单封装, `container`默认为`document.body`。
```js
import { $ } from 'wkit'
let $foo = $('.foo')
$foo.onclick = function(){ /* ... */ }
```
### \$$(selector`<String>`, container`<Dom>`)
> 原生`querySelectorAll()`的简单封装, 用法跟上面的一样, 区别是返回一个数组。
### bind(dom`<Dom>`, type`<String>`, selector`<String>`, fn`<Function>`, phase`<Any>`)
> 事件绑定的方法, 基于`addEventListener()`的封装。支持事件委托, 支持同时绑定多个事件。
```js
import { $, bind } from 'wkit'
let $input = $('.input')
bind($input, 'input', ev => { /* ... */ })
// 还可以同时绑定多个事件, 这对于不同事件, 都走同一套逻辑处理时, 非常方便
bind($input, 'input,change', ev => { /* ... */ })
```
同时, 还支持事件委托。这对长列表来说, 尤其有用, 即可避免过多的事件绑定产生额外的资源开销, 也可避免动态追加的数据, 没有事件绑定的尴尬。
```js
import { $, bind } from 'wkit'
html`
<ul class="list">
<li class="item">...</li>
...
</ul>
`
let $list = $('.list')
bind($list, 'click', '.item', ev => { /* ... */ })
```
### unbind(dom`<Dom>`, type`<String>`, fn`<Function>`, phase`<Any>`)
> 注销事件绑定。
```js
import { $, bind, unbind } from 'wkit'
let $input = $('.input')
// bind方法返回事件的回调函数
let callback = bind($input, 'input', ev => { /* ... */ })
// 注销绑定
unbind($input, 'input', callback)
```
### fire(dom`<Dom>`, name`<String>`, data`<Object>`, cancelBubble`<Boolean>`)
> 这是用于主动触发任意事件的方法, 其中, `data`的内容, 全合并进形参`event`中。`cancelBubble`为是否取消事件冒泡。为true时, 事件不会往上冒泡。
```js
import { $, bind, fire } from 'wkit'
let $input = $('.input')
bind($input, 'select', ev => {
console.log(ev.foo)
})
fire($input, 'select', { foo: 123 })
```
### outsideClick(dom`<Dom>`, fn`<Function>`)
> 一个很有用的事件绑定方法。该事件触发机制, 如它的名字所示, 即当鼠标在给定的节点对象外部(最外到body这一层)点击时, 就会触发。
### clearOutsideClick(fn`<Function>`)
> 注销上面的方法产生的事件绑定。因为这方法实际上是绑定在`document`上的, 所以注销事件时, 无需传入节点对象。
### offset(dom`<Dom>`)
> 取得距离页面左上角的坐标。 返回一个对象 `{top: xx, left: xx}`
### hyphen(val`<String>`)
> 将驼峰风格的字符串,转换为连字符风格
```js
import { hyphen } from 'wkit'
let name = 'FooBar'
hyphen(name) // foo-bar
```
### camelize(val`<String>`)
> 将连字符风格的字符串,转换为驼峰风格
```js
import { camelize } from 'wkit'
let name = 'foo-bar'
camelize(name) // fooBar
```
### range(start`<Number>`, end`<Number>`, step`<Number>`)
> 创建一个指定范围的, 元素连续的数组。
>> - start 数组的开始数值
>> - end 数组的最大数值(返回的数组, 元素中不包含该值)
>> - step 数组元素的步进大小, 只能是大于0的正整数。 默认为 1。
若传入的`start`比`end`大, 则自动调换这个值。`step`传入负数会强制转为其绝对值, 若传入`0`则强制改为`1`。
```js
import { range } from 'wkit'
range() // []
range(10) // [0,1,2,3,4,5,6,7,8,9]
range(0, 10) // [0,1,2,3,4,5,6,7,8,9]
range(10, 0) // [0,1,2,3,4,5,6,7,8,9]
range(0, 10, 2) // [0,2,4,6,8]
```
### nextTick(callback`<Function>`)
> 异步执行方法。