国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
observable
autorun
computed
Home Web Front-end JS Tutorial How to Manage Your JavaScript Application State with MobX

How to Manage Your JavaScript Application State with MobX

Feb 17, 2025 am 08:57 AM

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!'; // 此處觸發(fā)

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!'; // 觸發(fā)
person.firstName = 'Matthew!'; // 也觸發(fā)

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 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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

See all articles