js implements a simple MVVM framework example sharing
This article mainly shares with you an example of a simple MVVM framework implemented in js. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help 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 the 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, It can be a json object or a function, and then define data-context="[controller name]" on the top-level element to bind the controller to all elements under the 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. Yes, an error will be prompted if the value is 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 be seen that the first four They just 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 (receiving the current observer parameters), and 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
Binding event syntax: on-{event}="{controller method}, type=on/one", the right side of the controller method is optional Parameters, currently only binding type on/one, 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 dom. You can initialize parameters on this method; created is after compiling 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 have a set of common components when doing projects, so they can be extended as follows. By default, the corresponding components are mounted to all controller examples Next, you can call it directly under the corresponding method: this.http.post();
However, there is a suggestion, which is to try to point the scope of the callback method to the controller as much as possible, so that development will not be easy. As for the scope problem that always occurs.
$.controller.extend({ utils: utils, notify: $.notify, modal: $.modal, http: $.http, alert: $.alert })
7. Principle and code analysis (to be continued...)
The entire js code is only more than 300 lines, so the implementation is relatively simple, and there are many aspects that have not been considered. There are also some functions that I want to implement but have not done yet. Currently, array change detection and local update of related DOM are not supported.
Related recommendations:
Introduce what MVC, MVP and MVVM are respectively
What is MVVM architecture and data binding ?
The above is the detailed content of js implements a simple MVVM framework example sharing. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

According to benchmarks, for small, high-performance applications, Quarkus (fast startup, low memory) or Micronaut (TechEmpower excellent) are ideal choices. SpringBoot is suitable for large, full-stack applications, but has slightly slower startup times and memory usage.

Writing clear and comprehensive documentation is crucial for the Golang framework. Best practices include following an established documentation style, such as Google's Go Coding Style Guide. Use a clear organizational structure, including headings, subheadings, and lists, and provide navigation. Provides comprehensive and accurate information, including getting started guides, API references, and concepts. Use code examples to illustrate concepts and usage. Keep documentation updated, track changes and document new features. Provide support and community resources such as GitHub issues and forums. Create practical examples, such as API documentation.

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

Java framework learning roadmap for different fields: Web development: SpringBoot and PlayFramework. Persistence layer: Hibernate and JPA. Server-side reactive programming: ReactorCore and SpringWebFlux. Real-time computing: ApacheStorm and ApacheSpark. Cloud Computing: AWS SDK for Java and Google Cloud Java.

There are five misunderstandings in Go framework learning: over-reliance on the framework and limited flexibility. If you don’t follow the framework conventions, the code will be difficult to maintain. Using outdated libraries can cause security and compatibility issues. Excessive use of packages obfuscates code structure. Ignoring error handling leads to unexpected behavior and crashes.
