基于jQuery的500行小型响应式框架jQvm

1,347 阅读1分钟

因为做一个用于生成水印的小型工具,使用到electron作为壳,在选ui框架的时候,当然是首先想到vue,但是经过一会儿使用后,发现vue机制在electron下面无法直接使用脚本引入方式,有些遗憾,于是打算直接使用jquery。但是写了一会儿之后,又觉得别扭,写react和vue太久,通过修改状态来触发界面重绘,这种方式实在太顺手了,现在去写jquery的代码,实在有些回不去的感觉。

于是乎,我自己写了一个基于jquery的响应式插件,也可以把它当作是一个小框架。

github.com/tangshuang/…

具体使用方法如下:

<script src="https://unpkg.com/jquery/dist/jquery.min.js"></script>
<script src="https://unpkg.com/jqvm/dist/jqvm.min.js"></script>

<template id="app">
  <span>{{name}}</span>
  <span>{{age}}</span>
  <button>grow</button>
</template>

<script>
$('#app')
  .vm({
    name: 'tomy',
    age: 12,
  })
  .on('click', 'button', state => {
    state.age ++
  })
  .mount()
</script>

以上就是最简单的用法。模板定义和vue差不多,但是有个大的区别,vue直接在模板里面绑定事件,但是在jqvm中通过传统的jquery的on绑定事件。

它有一些内置的directive(指令),最常用的应该是jq-if了。

<template>
  <div jq-if="isTouched">xxx</div>
</template>

还可以在mount 之前注册一些component和directive。

const { component, directive } = $.vm

component('icon', function(el, attrs) {
  const { type } = attrs
  return `<i class="icon icon-${type}"></i>`
})

directive('jq-link', function(el, attrs) {
  const link = attrs['jq-link']
  const to = this.parse(link) // this.parse 是一个内置服务,用来将字符串解析成 state 上的对应值
  el.attr('href', to)
})

注册好之后,在模板里面使用。

<template>
  <icon type="search"></icon>
  <a jq-link="xxx">jump</a>
</template>

再来说说设计理念,我的想法,就是“简单”。使用简单,也别整特别多概念,虽然我前面提到vm, state之类的,一看基本上都能明白咋回事,拿过来就撸,别想那么多。不过还是需要再解释一下on那里怎么绑定事件,第三个参数是一个函数,这个函数接收state,这个state被修改就会重新渲染,这个函数返回一个函数,返回的这个函数就是正常情况下我们用 jquery.fn.on绑定的时候传入的那个函数。

$('#app')
  .vm({ ... })
  .on('click', 'button', state => function(e) {
    const color = $(this).css('color')
    state.color = color
    // ...
  })

这个小框架打包压缩之后,总体体积不到50k,可以说麻雀虽小,五脏俱全。也没有啥特别新潮的东西,在一些需要1分钟内开始界面编程的场景,再适合不过了。

github.com/tangshuang/…

如果你觉得这个项目有点意思,给个star吧。


关注我都公众号,一起讨论前端技术