Home > Web Front-end > JS Tutorial > How to Manage Your JavaScript Application State with MobX

How to Manage Your JavaScript Application State with MobX

Christopher Nolan
Release: 2025-02-17 08:57:08
Original
603 people have browsed it

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;
  }
};
Copy after login
Copy after login

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;
  }
};
Copy after login
Copy after login

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});
Copy after login

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;
  }
});
Copy after login

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!'; // 此处触发
Copy after login

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!'; // 也触发
Copy after login

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);
Copy after login

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);
});
Copy after login

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);
Copy after login
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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template