Mantra how-to guide
How to extend MantraAPI object in client
Mantra defines a client object that can be extended in with methods and properties in each request
Despite you can develop backend projects with Mantra, the framework has been designed to run web projects as well following HTML standards.
By default, Mustache is used to compose the final HTML document to send on each request, but you can use any UI framework or library to be used in the client, such as Angular, Vue, etc.
A typical situation in web development occurs when you need to send data to the client in a request, this is, the javacript code that will be run in the browser (the client), not in the backend (the server).
In each web request (when the user points to any route in the browser), Mantra defines an object called MantraAPI (don't confuse with Mantra API general object that is used in the backend in each interaction).
By default, that object is empty, but you can add methods and properties to be used in the client during the processing of the request.
You can define in your component a js file that adds methods to that object, like this example:
MantraAPI.PostAsync = function( component, command, data ) {
return new Promise( (resolve,reject) => {
let url = "/"+component+"/"+command;
let dataToSend = JSON.stringify(data);
$.ajax( {
method: "POST",
type: "POST",
url: url,
data: { mantraPostData: dataToSend }
})
.done( function(result) { resolve(result); })
.fail( function( jqXHR, msg ) { reject(jqXHR.responseJSON); })
});
}
MantraAPI.RedirectTo = function( url ) {
window.location = url;
}
In this case, two methods are added to MantraAPI object (PostAsync and RedirectTo). Those methods will be available for any javacript code running in the client.
You can also add some data pieces to MantraAPI.
To do that, in the view of the component, you can use Mantra.AddDataValue() API method to add data given its name, like this example:
Mantra.AddDataValue( "booktitle", "Lord of the Rings");
All properties (values) added this that method, will be se in MantraAPI.data property.
With these two simple mecanisms, you can set all stuff you need to expose in the client MantraAPI values and methods in each request in a coherent way.