Components



Application architecture with components

Components are versatile tools to organize code and can be used in a variety of ways.

Let’s create a simple model entity which we’ll use in a simple application, to illustrate different usage patterns for components:

  1. var Contact = function(data) {
  2. data = data || {}
  3. this.id = m.prop(data.id || "")
  4. this.name = m.prop(data.name || "")
  5. this.email = m.prop(data.email || "")
  6. }
  7. Contact.list = function(data) {
  8. return m.request({method: "GET", url: "/api/contact", type: Contact})
  9. }
  10. Contact.save = function(data) {
  11. return m.request({method: "POST", url: "/api/contact", data: data})
  12. }

Here, we’ve defined a class called Contact. A contact has an id, a name and an email. There are two static methods: list for retrieving a list of contacts, and save to save a single contact. These methods assume that the AJAX responses return contacts in JSON format, containing the same fields as the class.

Aggregation of responsibility

One way of organizing components is to use component parameter lists to send data downstream, and to define events to bubble data back upstream to a centralized module who is responsible for interfacing with the model layer.

  1. var ContactsWidget = {
  2. controller: function update() {
  3. this.contacts = Contact.list()
  4. this.save = function(contact) {
  5. Contact.save(contact).then(update.bind(this))
  6. }.bind(this)
  7. },
  8. view: function(ctrl) {
  9. return [
  10. m.component(ContactForm, {onsave: ctrl.save}),
  11. m.component(ContactList, {contacts: ctrl.contacts})
  12. ]
  13. }
  14. }
  15. var ContactForm = {
  16. controller: function(args) {
  17. this.contact = m.prop(args.contact || new Contact())
  18. },
  19. view: function(ctrl, args) {
  20. var contact = ctrl.contact()
  21. return m("form", [
  22. m("label", "Name"),
  23. m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
  24. m("label", "Email"),
  25. m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
  26. m("button[type=button]", {onclick: args.onsave.bind(this, contact)}, "Save")
  27. ])
  28. }
  29. }
  30. var ContactList = {
  31. view: function(ctrl, args) {
  32. return m("table", [
  33. args.contacts().map(function(contact) {
  34. return m("tr", [
  35. m("td", contact.id()),
  36. m("td", contact.name()),
  37. m("td", contact.email())
  38. ])
  39. })
  40. ])
  41. }
  42. }
  43. m.mount(document.body, ContactsWidget)

In the example above, there are 3 components. ContactsWidget is the top level module being rendered to document.body, and it is the module that has the responsibility of talking to our Model entity Contact, which we defined earlier.

The ContactForm component is, as its name suggests, a form that allows us to edit the fields of a Contact entity. It exposes an event called onsave which is fired when the Save button is pressed on the form. In addition, it stores the unsaved contact entity internally within the component (this.contact = m.prop(args.contact || new Contact())).

The ContactList component displays a table showing all the contact entities that are passed to it via the contacts argument.

The most interesting component is ContactsWidget:

  1. on initialization, it fetches the list of contacts (this.contacts = Contact.list)

  2. when save is called, it saves a contact (Contact.save(contact))

  3. after saving the contact, it reloads the list (.then(update.bind(this)))

update is the controller function itself, so defining it as a promise callback simply means that the controller is re-initialized after the previous asynchronous operation (Contact.save())

Aggregating responsibility in a top-level component allows the developer to manage multiple model entities easily: any given AJAX request only needs to be performed once regardless of how many components need its data, and refreshing the data set is simple.

In addition, components can be reused in different contexts. Notice that the ContactList does not care about whether args.contacts refers to all the contacts in the database, or just contacts that match some criteria. Similarly, ContactForm can be used to both create new contacts as well as edit existing ones. The implications of saving are left to the parent component to handle.

This architecture can yield highly flexible and reusable code, but flexibility can also increase the cognitive load of the system (for example, you need to look at both the top-level module and ContactList in order to know what is the data being displayed (and how it’s being filtered, etc). In addition, having a deeply nested tree of components can result in a lot of intermediate “pass-through” arguments and event handlers.


Distribution of concrete responsibilities

Another way of organizing code is to distribute concrete responsibilities across multiple modules.

Here’s a refactored version of the sample app above to illustrate:

  1. var ContactForm = {
  2. controller: function() {
  3. this.contact = m.prop(new Contact())
  4. this.save = function(contact) {
  5. Contact.save(contact)
  6. }
  7. },
  8. view: function(ctrl) {
  9. var contact = ctrl.contact()
  10. return m("form", [
  11. m("label", "Name"),
  12. m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
  13. m("label", "Email"),
  14. m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
  15. m("button[type=button]", {onclick: ctrl.save.bind(this, contact)}, "Save")
  16. ])
  17. }
  18. }
  19. var ContactList = {
  20. controller: function() {
  21. this.contacts = Contact.list()
  22. },
  23. view: function(ctrl) {
  24. return m("table", [
  25. ctrl.contacts().map(function(contact) {
  26. return m("tr", [
  27. m("td", contact.id()),
  28. m("td", contact.name()),
  29. m("td", contact.email())
  30. ])
  31. })
  32. ])
  33. }
  34. }
  35. m.route(document.body, "/", {
  36. "/list": ContactList,
  37. "/create": ContactForm
  38. })

Notice that now each component is self-contained: each has a separate route, and each component does exactly one thing. These components are designed to not interface with other components. On the one hand, it’s extremely easy to reason about the behavior of the components since they only serve a single purpose, but on the other hand they don’t have the flexibility that the previous example did (e.g. in this iteration, ContactList can only list all of the contacts in the database, not an arbitrary subset.

Also, notice that since these components are designed to encapsulate their behavior, they cannot easily affect other components. In practice, this means that if the two components were in a ContactsWidget component as before, saving a contact would not update the list without some extra code.

Cross-communication in single-purpose components

Here’s one way to implement cross-communication between single purpose components:

  1. var Observable = function() {
  2. var controllers = []
  3. return {
  4. register: function(controller) {
  5. return function() {
  6. var ctrl = new controller
  7. ctrl.onunload = function() {
  8. controllers.splice(controllers.indexOf(ctrl), 1)
  9. }
  10. controllers.push({instance: ctrl, controller: controller})
  11. return ctrl
  12. }
  13. },
  14. trigger: function() {
  15. controllers.map(function(c) {
  16. ctrl = new c.controller
  17. for (var i in ctrl) c.instance[i] = ctrl[i]
  18. })
  19. }
  20. }
  21. }.call()
  22. var ContactsWidget = {
  23. view: function(ctrl) {
  24. return [
  25. ContactForm,
  26. ContactList
  27. ]
  28. }
  29. }
  30. var ContactForm = {
  31. controller: function() {
  32. this.contact = m.prop(new Contact())
  33. this.save = function(contact) {
  34. Contact.save(contact).then(Observable.trigger)
  35. }
  36. },
  37. view: function(ctrl) {
  38. var contact = ctrl.contact()
  39. return m("form", [
  40. m("label", "Name"),
  41. m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
  42. m("label", "Email"),
  43. m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
  44. m("button[type=button]", {onclick: ctrl.save.bind(this, contact)}, "Save")
  45. ])
  46. }
  47. }
  48. var ContactList = {
  49. controller: Observable.register(function() {
  50. this.contacts = Contact.list()
  51. }),
  52. view: function(ctrl) {
  53. return m("table", [
  54. ctrl.contacts().map(function(contact) {
  55. return m("tr", [
  56. m("td", contact.id()),
  57. m("td", contact.name()),
  58. m("td", contact.email())
  59. ])
  60. })
  61. ])
  62. }
  63. }
  64. m.mount(document.body, ContactsWidget)

In this iteration, both the ContactForm and ContactList components are now children of the ContactsWidget component and they appear simultaneously on the same page.

The Observable object exposes two methods: register which marks a controller as a Observable entity, and trigger which reloads controllers marked by register. Controllers are deregistered when their onunload event is triggered.

The ContactList component’s controller is marked as Observable, and the save event handler in ContactForm calls Observable.trigger after saving.

This mechanism allows multiple components to be reloaded in response to non-idempotent operations.

One extremely important aspect of this architecture is that since components encapsulate their internal state, then by definition it’s harder to reason about AJAX request redundancy (i.e. how to prevent two identical AJAX requests originating from two different components).

The observer pattern

The Observable object can be further refactored so that trigger broadcasts to “channels”, which controllers can subscribe to. This is known, appropriately, as the observer pattern.

  1. var Observable = function() {
  2. var channels = {}
  3. return {
  4. register: function(subscriptions, controller) {
  5. return function self() {
  6. var ctrl = new controller
  7. var reload = controller.bind(ctrl)
  8. Observable.on(subscriptions, reload)
  9. ctrl.onunload = function() {
  10. Observable.off(reload)
  11. }
  12. return ctrl
  13. }
  14. },
  15. on: function(subscriptions, callback) {
  16. subscriptions.forEach(function(subscription) {
  17. if (!channels[subscription]) channels[subscription] = []
  18. channels[subscription].push(callback)
  19. })
  20. },
  21. off: function(callback) {
  22. for (var channel in channels) {
  23. var index = channels[channel].indexOf(callback)
  24. if (index > -1) channels[channel].splice(index, 1)
  25. }
  26. },
  27. trigger: function(channel, args) {
  28. console.log("triggered: " + channel)
  29. channels[channel].map(function(callback) {
  30. callback(args)
  31. })
  32. }
  33. }
  34. }.call()

This pattern is useful to decouple chains of dependencies (however care should be taken to avoid “come-from hell”, i.e. difficulty in following a chains of events because they are too numerous and arbitrarily inter-dependent)

Hybrid architecture

It’s of course possible to use both aggregation of responsibility and the observer pattern at the same time.

The example below shows a variation of the contacts app where ContactForm is responsible for saving.

  1. var ContactsWidget = {
  2. controller: Observable.register(["updateContact"], function() {
  3. this.contacts = Contact.list()
  4. }),
  5. view: function(ctrl) {
  6. return [
  7. m.component(ContactForm),
  8. m.component(ContactList, {contacts: ctrl.contacts})
  9. ]
  10. }
  11. }
  12. var ContactForm = {
  13. controller: function(args) {
  14. this.contact = m.prop(new Contact())
  15. this.save = function(contact) {
  16. Contact.save(contact).then(Observable.trigger("updateContact"))
  17. }
  18. },
  19. view: function(ctrl, args) {
  20. var contact = ctrl.contact()
  21. return m("form", [
  22. m("label", "Name"),
  23. m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
  24. m("label", "Email"),
  25. m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
  26. m("button[type=button]", {onclick: ctrl.save.bind(this, contact)}, "Save")
  27. ])
  28. }
  29. }
  30. var ContactList = {
  31. view: function(ctrl, args) {
  32. return m("table", [
  33. args.contacts().map(function(contact) {
  34. return m("tr", [
  35. m("td", contact.id()),
  36. m("td", contact.name()),
  37. m("td", contact.email())
  38. ])
  39. })
  40. ])
  41. }
  42. }
  43. m.mount(document.body, ContactsWidget)

Here, the data fetching is still centralized in the top-level component, so that we can avoid duplicate AJAX requests when fetching data.

And moving the responsibility of saving to the ContactForm component alleviates the need to send data back up the component tree, making the handling of non-idempotent operations less prone to pass-through argument noise.


Classic MVC

Here’s one last, but relevant variation of the pattern above.

  1. //model layer observer
  2. Observable.on(["saveContact"], function(data) {
  3. Contact.save(data.contact).then(Observable.trigger("updateContact"))
  4. })
  5. //ContactsWidget is the same as before
  6. var ContactsWidget = {
  7. controller: Observable.register(["updateContact"], function() {
  8. this.contacts = Contact.list()
  9. }),
  10. view: function(ctrl) {
  11. return [
  12. m.component(ContactForm),
  13. ctrl.contacts() === undefined
  14. ? m("div", "loading contacts...") //waiting for promise to resolve
  15. : m.component(ContactList, {contacts: ctrl.contacts})
  16. ]
  17. }
  18. }
  19. //ContactList no longer calls `Contact.save`
  20. var ContactForm = {
  21. controller: function(args) {
  22. var ctrl = this
  23. ctrl.contact = m.prop(new Contact())
  24. ctrl.save = function(contact) {
  25. Observable.trigger("saveContact", {contact: contact})
  26. ctrl.contact = m.prop(new Contact()) //reset to empty contact
  27. }
  28. return ctrl
  29. },
  30. view: function(ctrl, args) {
  31. var contact = ctrl.contact()
  32. return m("form", [
  33. m("label", "Name"),
  34. m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
  35. m("label", "Email"),
  36. m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
  37. m("button[type=button]", {onclick: ctrl.save.bind(this, contact)}, "Save")
  38. ])
  39. }
  40. }
  41. //ContactList is the same as before
  42. var ContactList = {
  43. view: function(ctrl, args) {
  44. return m("table", [
  45. args.contacts().map(function(contact) {
  46. return m("tr", [
  47. m("td", contact.id()),
  48. m("td", contact.name()),
  49. m("td", contact.email())
  50. ])
  51. })
  52. ])
  53. }
  54. }
  55. m.mount(document.body, ContactsWidget)

Here we’ve moved Contact.save(contact).then(Observable.trigger("updateContact")) out of the ContactForm component and into the model layer. In its place, ContactForm merely emits an action, which is then handled by this model layer observer.

This allows swapping the implementation of the saveContact handler without changing the ContactForm component.


Example: HTML5 drag-n-drop file uploader component

Here’s an example of a not-so-trivial component: a drag-n-drop file uploader. In addition to the controller and view properties that make the Uploader object usable as a component, it also has an upload convenience function that provides a basic upload model method, and a serialize function that allows files to be serialized as JSON in regular requests encoded as application/x-www-form-urlencoded.

These two functions are here to illustrate the ability to expose APIs to component consumers that complement the component’s user interface. By bundling model methods in the component, we avoid hard-coding how files are handled once they’re dropped in, and instead, we provide a useful library of functions that can be consumed flexibly to meet the demands on an application.

  1. var Uploader = {
  2. upload: function(options) {
  3. var formData = new FormData
  4. for (var key in options.data) {
  5. for (var i = 0; i < options.data[key].length; i++) {
  6. formData.append(key, options.data[key][i])
  7. }
  8. }
  9. //simply pass the FormData object intact to the underlying XMLHttpRequest, instead of JSON.stringify'ing it
  10. options.serialize = function(value) {return value}
  11. options.data = formData
  12. return m.request(options)
  13. },
  14. serialize: function(files) {
  15. var promises = files.map(function(file) {
  16. var deferred = m.deferred()
  17. var reader = new FileReader
  18. reader.readAsDataURL()
  19. reader.onloadend = function(e) {
  20. deferred.resolve(e.result)
  21. }
  22. reader.onerror = deferred.reject
  23. return deferred.promise
  24. })
  25. return m.sync(promises)
  26. },
  27. controller: function(args) {
  28. this.noop = function(e) {
  29. e.preventDefault()
  30. }
  31. this.update = function(e) {
  32. e.preventDefault()
  33. if (typeof args.onchange == "function") {
  34. args.onchange([].slice.call((e.dataTransfer || e.target).files))
  35. }
  36. }
  37. },
  38. view: function(ctrl, args) {
  39. return m(".uploader", {ondragover: ctrl.noop, ondrop: ctrl.update})
  40. }
  41. }

Below are some examples of consuming the Uploader component:

  1. //usage demo 1: standalone multipart/form-data upload when files are dropped into the component
  2. var Demo1 = {
  3. controller: function() {
  4. return {
  5. upload: function(files) {
  6. Uploader.upload({method: "POST", url: "/api/files", data: {files: files}}).then(function() {
  7. alert("uploaded!")
  8. })
  9. }
  10. }
  11. },
  12. view: function(ctrl) {
  13. return [
  14. m("h1", "Uploader demo"),
  15. m.component(Uploader, {onchange: ctrl.upload})
  16. ]
  17. }
  18. }

Demo

  1. //usage demo 2: upload as base-64 encoded data url from a parent form
  2. var Demo2 = {
  3. Asset: {
  4. save: function(data) {
  5. return m.request({method: "POST", url: "/api/assets", data: data})
  6. }
  7. },
  8. controller: function() {
  9. var files = m.prop([])
  10. return {
  11. files: files,
  12. save: function() {
  13. Uploader.serialize(files()).then(function(files) {
  14. Demo2.Asset.save({files: files}).then(function() {
  15. alert("Uploaded!")
  16. })
  17. })
  18. }
  19. }
  20. },
  21. view: function(ctrl) {
  22. return [
  23. m("h1", "Uploader demo"),
  24. m("p", "Drag and drop a file below. An alert box will appear when the upload finishes"),
  25. m("form", [
  26. m.component(Uploader, {onchange: ctrl.files}),
  27. ctrl.files().map(function(file) {
  28. return file.name
  29. }).join(),
  30. m("button[type=button]", {onclick: ctrl.save}, "Upload")
  31. ])
  32. ]
  33. }
  34. }

Demo