The loopLesson 12 of 23

What does a message know?

Carry data in a message, and keep a field showing exactly what the Model holds.

ClickedIncrement said everything in its name. Typing is different. "They typed something" is not enough to act on. The message has to bring what they typed with it.

Predict

Read the view in Greeting.ts. The field is given .value(model.name) and nothing else. No handler reports what happens to it.

Click into the field and type a few letters in your head. What does the field show afterwards?

Check your answer

It still shows "Ada". Try it.

The field was told to show model.name. You typed, but nothing told update, so the Model didn't change, so the field shows what it showed before. The log has no new row. As far as this component knows, nothing happened.

Try it

  1. Report the typing. Chain a handler onto the input, after .value(model.name):

    .on("input", ({ value }) => GreetingMessage.UpdatedName({ name: value }))

    Press Run and type "Grace". Before you do: how many rows will the log gain?

  2. Open one of the new rows. Where did the letters you typed end up?

  3. Let update have an opinion. Add const limit = 12 above the component and change the handler to $.evolve({ name: name.slice(0, limit) }). Before you type a thirteenth letter: what will the field do?

  4. Add a second fact, ToggledShout: { shout: Schema.Boolean }, with a shout field in the Model and init. Draw a checkbox with .checked(model.shout) and .on("change", ({ checked }) => GreetingMessage.ToggledShout({ shout: checked })), and show the greeting in capitals while it is on.

About steps 1 and 3

Five rows, one for each letter. Each is UpdatedName, and its payload holds the whole text of the field at that moment.

In step 3 the thirteenth letter never appears. The field didn't refuse it. The message arrived with thirteen letters, update kept twelve, and the field shows the Model.

What you found

A message is a fact, and a fact can carry data. The handler here is a function. The runtime gives it what the event reports, { value } for typing and { checked } for a checkbox, and it returns a message with that inside. update receives the payload as its second argument.

The text lives in one place, the Model. The field is not a second copy that has to be kept in step. It shows the Model, typing sends a message, update decides, and the field shows the result. That is why one line in update could cap the name, and why the field could never disagree with the greeting under it.

A payload can also say which one. A page with twenty rows doesn't need twenty messages. So how do you change one thing in a list?

12
Principle 12

One source of truth

A field shows what the Model holds. Typing sends a message, the Model changes, the field shows the result. There is no second copy to drift.

ResultStarting

No messages yet

Use the example above. Each message that reaches update shows here, with what it changed.