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
autorun
Implements MobX's 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
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
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.
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.
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);
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
(The following content omits some code examples and detailed explanations, and retains the core content and structure)
Put MobX into useLet'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
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!