DEV Community

frustigor
frustigor

Posted on

Write a small frontend reactive view-model framework based on jQuery with less than 500 lines code

Alt Text

Last weekend I wrote a small tool which helps photo producers to bind watermark to their pictures. The tool is very easy and is written in Electron and jQuery. However, I have used Vue and React for a long time, it is sometimes awkward back to an old tech. So after I finished the tool, I summarized the practice and wrote a small reactive view-model for jQuery.

<template id="app">
  <div class="title">{{title}}</div>
  <div class="content">{{content}}</div>
  <div class="view-count">View: {{view}}</div>
</template>
const view = $('#app')
  .vm({
    title: 'Title',
    content: 'JQVM is a small frontend jquery plugin, and even a framework.',
    view: 0,
  })
  .on('click', state => function(e) {
    state.view ++
  })
  .mount()

The template part is very like vue's template, but we do not announce event listeners in template. Events are bound with on as jQuery does. The listener callback function is a combination of currying function. state is point to inner vm state, when you change the state, the view will rerender.

The core code is less than 500 lines, you can find the source code here. After minizing, the bundle file's size is only 46k (without jQuery). Small is beautiful.

https://github.com/tangshuang/jqvm

JQVM is not built with virtual dom, it is not used to build big applications, it is used to help jQuery lovers to setup a small app quickly and enjoy the reactive programming. Just play it with CDN, as you imported jQuery before. Believe me, you can setup a jqvm app in 10 seconds!

Top comments (0)