Backbone enables you to define model classes which can be bound to views (e.g. HTML forms). Backbone keeps track of updating the model when the user interacts with the UI and vice versa. It also aids you by synchronizing your model with the server, e.g. by calling the appropriate method of your REST handler on the server side. So you end up implementing business logic in your front-end code, leaving your server model responsible for persisting data.
The Java Model
First, we define a domain class
Product in java code. This class might be used for CRUD database operations (saving to and loading from a datasource). Keep in mind that this class is a dumb Java Bean without any business logic applied, because we want our front-end to be capable of executing the business logic right from the UI.
The Backbone Model
Now we define the backbone model as the counter-part of our java bean. The backbone model
Product uses the same data-structure as the java bean, since this is the data we might want to persist on the java server.
The backbone model also implements the business logic: The method
getValueOfGoods calculates the value of all products by multiplying
price. Each time
price changes the property
valueOfGoods must be re-calculated.
Since the backbone model doesn't use any Nashorn language extensions, we can safely use the same code both on the client (Browser) and on the server (Java) side.
Keep in mind that I deliberately chose a really simple function for demonstrating purposes only. Real business logic should be more complex.
Putting both together
The next goal is to re-use the backbone model from Nashorn, e.g. on the java server. We want to achieve the following behavior: bind all properties from the java bean to the backbone model; calculate the property
valueOfGoods; pass the result back to java.
First, we create a new script to be evaluated solely by Nashorn, so we can safely use Nashorn extensions here:
calculate accepts a
Product java bean, binds all properties to a newly created backbone
Product and returns all attributes of the model back to the caller. By setting the properties
price on the backbone model, property
valueOfGoods will automatically be calculated due to the event handler registered in the models
initialize constructor function.
Finally, we call the function
calculate from java:
We create a new
getValueOfGoods will be triggered, so we can read the property
valueOfGoods from the returning object.