search
HomeWeb Front-endJS TutorialHow to Manage Your JavaScript Application State with MobX

How to Manage Your JavaScript Application State with MobX

How to Manage Your JavaScript Application State with MobX

This article was peer-reviewed by Michel Weststrate and Aaron Boyer. Thanks to all the peer reviewers of SitePoint for making SitePoint’s content perfect!

If you have ever written an application that is more complex than a very simple one using jQuery, you may have had the problem of keeping different parts of the UI in sync. Often, changes to data need to be reflected in multiple locations, and as the application grows, you may find yourself in trouble. To control this confusion, events are often used to let different parts of the application know when changes have occurred.

So, how did you manage the application status today? I'm going to take the liberty to say that you oversubscribe to the changes. That's right. I don't even know you, but I'm going to point it out. If you are not oversubscribe, then I'm sure you've worked too hard.

Of course, unless you use MobX…

Key Points

  • Simplify state management with MobX: Efficiently manage application state through observable objects, reducing the complexity and boilerplate code found in other state management libraries such as Redux.
  • MobX automatic update: Implement MobX's autorunImplements MobX's
  • function to update UI components automatically in response to state changes without manual event processing, thus simplifying the synchronization process of the entire application.
  • Enhance performance with computed values:
  • Use computed values ​​from MobX to derive data from state, ensuring that components are re-rendered only when necessary, thereby improving overall application performance.
  • MobX is easy to get started:
  • Seamlessly integrate MobX into existing JavaScript applications by converting standard objects into observable objects, allowing for gradual adoption without full rewriting.
  • Transactional modification with MobX operations:
  • Apply MobX operations to encapsulate state modifications in transactions, thereby batch updates and minimizes redundant rendering, resulting in more efficient and less error-prone code .

What is "state"?

fullName()This is a character. Hey, that's me! I have a firstName, lastName and age. Also, if I have trouble, the

function may appear.
var person = {
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 37,
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  }
};

How will you notify your various outputs (views, servers, debug logs) of modifications to this person? When will you trigger these notifications? Before MobX, I would use a setter that triggers a custom jQuery event or js-signals. These options serve me well, but my usage of them is far from meticulous. If any part of the person object changes, I will trigger a "changed" event.

Suppose I have a view code that shows my name. If I change my age, the view will be updated as it is bound to the changed event of that person.
var person = {
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 37,
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  }
};

How do we tighten this overtrigger? Simple. Simply set a setter for each field and set a separate event for each change. Wait - If you want to change the age and firstName at once, you may start overtriggering. You have to create a way to delay event firing until both changes are complete. It sounds like work, and I'm lazy...

MobX comes to rescue

MobX is a simple, focused, efficient and inconspicuous state management library developed by Michel Weststrate.

From MobX documentation:

Simply do something about the state and MobX will make sure your application respects these changes.

person.events = {};

person.setData = function (data) {
  $.extend(person, data);
  $(person.events).trigger('changed');
};

$(person.events).on('changed', function () {
  console.log('first name: ' + person.firstName);
});

person.setData({age: 38});

Did you notice the difference? mobx.observable is the only change I made. Let's check out the console.log example again:

var person = mobx.observable({
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 37,
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  }
});

Using autorun, MobX will only observe the content that has been accessed.

If you think this is neat, check out the following:

mobx.autorun(function () {
  console.log('first name: ' + person.firstName);
});

person.age = 38; // 打印为空
person.lastName = 'RUBY!'; // 仍然为空
person.firstName = 'Matthew!'; // 此处触发

Interested? I know you are interested.

MobX core concept

observable

mobx.autorun(function () {
  console.log('Full name: ' + person.fullName);
});

person.age = 38; // 打印为空
person.lastName = 'RUBY!'; // 触发
person.firstName = 'Matthew!'; // 也触发

MobX observable objects are just objects. In this example, I'm not observing anything. This example shows how to start integrating MobX into your existing code base. Just use mobx.observable() or mobx.extendObservable() to get started.

autorun

var log = function(data) {
  $('#output').append('' +data+ '');
}

var person = mobx.observable({
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 34
});

log(person.firstName);

person.firstName = 'Mike';
log(person.firstName);

person.firstName = 'Lissy';
log(person.firstName);

What do you want to do when your observables change, right? Let me introduce autorun(), which will trigger a callback when any referenced observable value changes. Note that in the example above, autorun() will not fire when the age changes.

computed

var person = mobx.observable({
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 0
});

mobx.autorun(function () {
  log(person.firstName + ' ' + person.age);
});

// 这将打印Matt NN 10次
_.times(10, function () {
  person.age = _.random(40);
});

// 这将什么也不打印
_.times(10, function () {
  person.lastName = _.random(40);
});

Did you see that fullName function? Note that it has no parameters and get? MobX will automatically create a calculated value for you. This is one of my favorite MobX features. Note that there is anything strange about person.fullName? Watch it again. This is a function, you can see the result without calling it! Usually, you will call person.fullName() instead of person.fullName. You just met your first JS getter.

The fun doesn't end here! MobX will monitor the dependencies of calculated values ​​for changes and only runs when they change. If nothing changes, the cached value will be returned. Please see the following situation:

var person = mobx.observable({
  firstName: 'Matt',
  lastName: 'Ruby',
  age: 0,
  get fullName () {
    return this.firstName + ' ' + this.lastName;
  }
});
log(person.fullName);

person.firstName = 'Mike';
log(person.fullName);

person.firstName = 'Lissy';
log(person.fullName);
You can see here that I've hit the

calculation multiple times, but the only time the function runs is when firstName or lastName changes. This is one of the ways MobX can greatly speed up applications. person.fullName

More!

I will not continue to rewrite the wonderful MobX documents anymore. Check out the documentation for more ways to use and create observable objects.

(The following content omits some code examples and detailed explanations, and retains the core content and structure)

Put MobX into use

Let's build something before it's too boring.

This is a simple non-MobX example that will show the full name of the person whenever it changes.

Note that even though we never changed the name, the name was rendered 10 times. You can optimize this problem using many events or check for some kind of change payload. This is too much work.

This is the same example built with MobX:

Note that there are no events, triggers, or on. With MobX, you are dealing with the latest value and the fact that it has changed. Note that it was rendered only once? This is because I haven't changed anything autorun is monitoring.

Let's build something slightly less trivial:

Here, we are able to edit the entire person object and automatically monitor the data output. Now, there are some soft points in this example, and the most notable thing is that the input value is out of sync with the person object. Let's solve this problem:

I know, you have another complaint: "Ruby, you've over-rendered!" You're right. This is why many people choose to use React. React allows you to easily break the output into widgets that can be rendered separately.

For completeness, here is a jQuery example I have optimized.

Will I do something like this in a real app? Probably not. If I need this granularity, I will use React at any time. When I use MobX and jQuery in a real application, I use a nuanced enough autorun() that I don't rebuild the entire DOM every time I change it.

You have come to this point, so here is the same example built with React and MobX

Let's build a slide show

How will you represent the status of the slide show? Let's start with a single slide factory:

We should have something to aggregate all of our slides. Let's build it now:

The slide show has begun! This is more interesting because we have an observable array of slides that allows us to add and remove slides from the collection and update our UI accordingly. Next, we add the activeSlide calculated value, which will keep itself up to date as needed.

Let's render our slide show. We are not ready for HTML output, so we will only print to the console.

It's cool, we have some slides, autorun just printed out their current status. Let's change one or two slides:

It looks like our autorun is working. If you change anything autorun is monitoring, it will fire. Let's change the output derivation from console to HTML:

We have now had the basic display of this slide show, but there is no interaction yet. You cannot click on the thumbnail and change the main image. However, you can easily change image text and add slideshow using the console:

Let's create our first and only action to set up the selected slideshow. We will have to modify slideShowModelFactory by adding:

You may ask, why do you need to use an operation? A good question! MobX operations are not required, as I have shown in other examples of changing observable values.

Operation will be helpful to you in several aspects. First, all MobX operations run in a transaction. This means that our autorun and other MobX reactions will wait for the operation to complete before triggering. Think about it. What happens if I try to deactivate the active slide outside the transaction and activate the next slide? Our autorun will be triggered twice. The first run will be awkward, as there will be no active slides available for display.

In addition to their transactional nature, MobX operations tend to make debugging easier. The first optional parameter I passed to mobx.action is the string "set active slide". This string can be output using MobX's debug API.

So we have our operation, let's use jQuery to connect it to:

That's it. You can now click on the thumbnail and the activity will propagate as expected. Here is a working example of a slide show:

This is an example of the same slide show using React.

Note, I didn't change the model at all? In terms of MobX, React is just another derivative of your data, such as jQuery or console.

Warnings for jQuery slide show example

Please note that I did not optimize the jQuery example in any way. We destroy the entire slide show DOM every time we change it. By breaking, I mean we replace all HTML for the slide show with each click. If you are building a powerful jQuery-based slide show, you may adjust the DOM after the initial rendering by setting and deleting the active class and changing the mainImage's attributes. src

Want to know more?

If you want to learn more about MobX, check out some other useful resources below:

If you have any questions, please let me know in the comments below, or find me in the MobX gitter channel.

FAQ on Managing JavaScript Application Status with MobX

(The FAQ part is omitted from the following content, because the article is too long and has little to do with the core content.)

The above is the detailed content of How to Manage Your JavaScript Application State with MobX. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.