top | item 23591366

(no title)

stefano | 5 years ago

You can have a nicely organized JS project without using a framework, albeit you can expect a bit more boilerplate.

There are many approaches you can take. The following is an MVC approach I'm trying out in a personal project. It's organized as follows:

There's a subscribe/emit system, where you can link functions to run when an object sends an emit signal. This can be done in a couple dozen lines of code. Example: https://gist.github.com/stefano/32cbe9bef5a68ecb3286113369d8...

Models are JavaScript objects. They have methods to read their state and to update it. The methods that update the state need to call emit() so all subscribers are notified.

Views are functions. They return an object with 2 properties: a DOM node (the root of the view), and an update function. The update function takes a model instance, and updates the DOM structure accordingly. If a view supports user interaction, it'll take a delegate object as a parameter. The view will add event handlers which call the delegate object. Example of a text input with a label and optional validation error: https://gist.github.com/stefano/2135cc15470cceba4ac2d344fe2e...

The controller is a function or class. It returns an object with its root view and a function to run when the controller is destroyed for cleanup. It can either take a model as a parameter or instantiate it. It also instantiates the root view, passing itself (or another object) as the delegate. In the delegate methods, it calls the model update methods. The controller subscribes the view to model changes, and unsubscribes them when it's destroyed. Alternatively, the view can subscribe/unsubscribe itself.

With this approach, views can be composed by calling the view functions from inside another view, passing down a delegate and adding the root DOM node to the parent view DOM structure.

The controller and the model are completely independent of the DOM. The model can be tested independently. The controller can be tested with a mock view. The view can be tested by passing in a mock model.

Views only depend on their initial state and the state of the model passed to the update function.

discuss

order

z3t4|5 years ago

The trick is to make as much as possible static. Just pure functions. Second trick is to have only one way direction, eg components only listen to events, they don't emit events, then they don't have to depend on each other, which in turn will lead to better reusability and less spaghetti.