Get from zero to a collaborative textarea in 10 minutes or less!
HTML Setup
We provide a Javascript API to help you build realtime applications. So what’s the simplest collaborative web application that you can think of? How about a realtime textarea? Two people can go to the same URL and use the same textarea at once. Just create the element, connect to Convergence, and bind to the model: we take care of all the events and data synchronization. Easy peasy.
Let’s lay out a basic example index.html that includes the Convergence javascript client and utilities and creates a simple textarea element:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/bundles/rxjs.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@convergence/convergence@latest/convergence.global.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@convergence/input-element-bindings@latest/browser/convergence-input-element-bindings.min.js"></script>
</head>
<body>
<h2>A Collaborative Text Area</h2>
<textarea id="textarea"></textarea>
<script type="text/javascript">
// See code snippets below
</script>
</body>
</html>
Next add the code from the following steps to the script tag in the index.html.
Connect
In Convergence, a ‘Domain’ encapsulates a set of data, users, messages, and other items. You can create as many domains as you want, perhaps representing projects, apps, or different environments (e.g. Staging). Thus, we first have to connect to a domain before doing anything else.
var domainUrl = "http://localhost:8000/api/realtime/convergence/default";
Convergence.connectAnonymously(domainUrl)
.then(initApp)
.catch((error) => {
console.log("Could not connect: " + error);
});
Open a Model
Data in a domain can be organized by collections of models. In this case, our model is simply an Object with a single string representing the contents of the textarea.
function initApp(domain) {
const modelService = domain.models();
// If the collection and/or model don't exist, they will be created for you.
modelService.openAutoCreate({
collection: "example",
model: "getting-started",
data: { text: "Hello World"}
})
.then(initModel)
.catch((error) => {
console.log("Could not open model: " + error);
});
}
Collaborate
Now that we have connected to the domain and opened a model, let’s work with the text area we added to the HTML file. We will need a reference to the RealTimeString within the model in order to both update it and listen for remote changes.
function initModel(model) {
const textArea = document.getElementById("textarea");
const realTimeString = model.elementAt("textValue");
// Sets the value of the text area and performs a two-way-binding.
ConvergenceInputElementBinder.bindTextInput(textArea, realTimeString);
}
We use the ConvergenceInputElementBinder to create a two-way binding between the textArea element and the string element within the Convergence model. And that’s it folks!
See Here for the complete example source code.