Below I will share with you an example of a simple MVVM framework implemented in js, which has a good reference value and I hope it will be helpful to everyone.
I used to read the articles in the garden silently and like them obscenely. Today I will also share a simple mvvm framework that I implemented using js.
At first, I only did automatic binding events. Later, I learned about vue, knockout and argular implementation methods, and combined with some of my own experience in making WPF, I added attribute binding. Today I sorted it out a little. Improved some functions and submitted the code to Code Cloud: https://gitee.com/zlj_fy/Simple-MVVM
Let’s briefly introduce the usage:
<form class="form-horizontal" role="form" data-context="TestController"> <p class="form-group"> <legend>Form title</legend> </p> <p class="form-group"> <p class="col-sm-6 col-sm-offset-2"> <input type="text" class="form-control" bind-val="age,format=format" style="margin:5px 0" /> <input type="text" class="form-control" bind-val="desc" style="margin:5px 0" /> <input type="range" min="10" max="300" bind-val="age" step="10" class="form-control" style="margin:5px 0" /> <input type="button" class="btn btn-primary" value="更新" style="margin:5px 0" on-click="update" /> </p> </p> </form> <script> var TestController = { data: { name: 'xiaoming', age: 3, desc: function() { return this.name + ' likes looking little movie. he should take care of his body' } }, format: function(val) { return val + '岁' }, update: function() { this.name = 'this is a test' this.age = 18 } } $('body').controller() </script>
First define a controller, which can be a json object or a function, and then define data-context="[controller name]" in the top-level element to bind the controller to All elements under this node. If there is a nested Controller in the descendants of the element, the scope of the child elements below the element it is located in points to the child controller.
1. Monitoring attributes and complex attributes
All attributes must be defined under the data node. If the attributes inside are defined as functions, they are considered complex attributes (such as desc) , complex attributes are read-only, and an error will be prompted if they are reassigned.
The format bound to the html element: "{attribute name,fomat=[controller method]}", the attribute name supports nested attributes, such as (a.b); the attribute name does not support expressions, consider If you feel it is not necessary, you can use complex attributes instead. The current disadvantage is that if the business is complex, a large number of complex attributes may be generated; on the right side of the attribute name are optional parameters. Currently, there is only format, which is the conversion method for attributes to be displayed on HTML.
2. Instruction
The binding instruction syntax is in the form of bind-{instruction}. Currently, only val, attr, text, html, and template are implemented. In fact, it can It can be seen that the first four simply encapsulate the jqeury method. The template is implemented using the jquery-tmpl plug-in. If you need more instructions, you can extend it yourself. You only need to implement the init initial loading method (receive the current observer parameter), and the update method (parameter description: corresponding jquery element, latest value, current controller instance); if you are extending an existing instruction, the original one will be overwritten by default. As follows:
$.controller.addDirective("val", { init: function (observer) { if (observer.$ele.is('input,select')) { //监听onchange事件 observer.$ele.on('input propertychange', function () { var newVal = $(this).val() observer.writeValue(newVal) }) } }, update: function ($ele, newVal, controller) { $ele.val && $ele.val(newVal) } })
3. Event
Bind event syntax: on-{event}="{controller method},type=on/one", control On the right side of the controller method are optional parameters. Currently, there are only binding types on/one, and the default is on; the controller method receives two parameters, one is the initial parameter that can be set on the element corresponding to the event, and the other is the event event parameter;
<button type="button" class="btn btn-primary" data-page="1" on-click="refesh">查询</button>
4. Method
Use this.property name directly to directly access the properties under the corresponding data node.
5. Hooks
init and created. Init is after monitoring all attributes and before compiling the dom. You can initialize parameters on this method; created is after compiling the dom elements. .
The controller implements the extend inheritance method by default, which can inherit another controller and must be used in the init method. Currently you can also use prototypal inheritance to implement it yourself.
init: function () { this.extend(PageController) }, created: function () { //TODO },
6. Extension
I believe that everyone will definitely have a set of common components when doing projects, then they can be extended as follows, and the corresponding components are mounted by default Go to all the controller examples and call them directly under the corresponding method: this.http.post();
But there is a suggestion, which is to try to uniformly point the scope of the callback method to Controller, so that scope problems will not always occur during development.
$.controller.extend({ utils: utils, notify: $.notify, modal: $.modal, http: $.http, alert: $.alert })
7. Principles and code analysis (to be continued...)
The entire js code is only more than 300 lines, so the implementation is relatively simple and has many aspects It has not been taken into account. There are also some functions that I want to implement but have not done. Currently, array change detection and local update of related DOM are not supported.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Details on using axios to solve http request problems in vue2 (detailed tutorial)
In vue Handle the problem of passing parameters in post requests through axios (detailed tutorial)
Add axios components through vue to solve the problem of null parameters in post (detailed tutorial)
Using the xe-utils function library in vue (detailed tutorial)
jQuery koa2 Example of implementing a simple Ajax request
The above is the detailed content of Implementing the MVVM framework in js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
