Cover by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Building an ORM

Object-relational mappers, or ORMs, are typically used in languages other than JavaScript. However, they’re a very useful technique for data management as well as a great way of using models in your JavaScript application. With an ORM, for example, you can tie up a model with a remote server—any changes to model instances will send background Ajax requests to the server. Or, you could tie up a model instance with an HTML element—any changes to the instance will be reflected in the view. I’ll elaborate on those examples later, but for now, let’s look at creating a custom ORM.

Essentially, an ORM is just an object layer wrapping some data. Typically, ORMs are used to abstract SQL databases, but in our case, the ORM will just be abstracting JavaScript data types. The advantage of this extra layer is that we can enhance the basic data with more functionality by adding our own custom functions and properties. This lets us add things like validation, observers, persistence, and server callbacks while still being able to reuse a lot of code.

Prototypal Inheritance

We’re going to use Object.create() to construct our ORM, which is a little different from the class-based examples we covered in Chapter 1. This will allow us to use prototype-based inheritance, rather than using constructor functions and the new keyword.

Object.create() takes one argument, a prototype object, and returns a new object with the specified prototype object. In other words, you give it an object, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required