I receive JSON objects from a websocket with update/create/delete flags. Based on this information, I either update, create or delete HTML elements and bind callbacks. This can affect multiple HTML elements.
My current approach was to put everything into specific objects which handle HTML generation via jquery e.g.:
$.("<table>").addChild($("<tr>")).addClass('test')
and bind event listeners. But with the addition of more and more code it got really messy and now im looking for a proper way to seperate the code.
Are there any ideas on how to do this properly? Frameworks? Maybe jQuery Templates (which still leaves me in the dark on how add callbacks cleanly)?
Look up the MVVM framework. This is exactly what you're needing as your JavaScript is getting increasingly more complex. It seperates your needs for concern between your Presentation code (html) and Presentation Logic (JavaSript)
Knockout.js is a really good library to get you started, I recommend going through the tutorials to get you started on it.
Quick example:
HelloWorld.html
<div data-bind="value: helloWorldVariable"></div>
<input type="button" data-bind="click: helloWorld" />
page.js:
var ViewModel = {
helloWorldVariable: ko.observable('test'),
helloWorld: function() {
this.helloWorldVariable('clicked!');
}
}
// Bind viewmodel
When the button is clicked, the div will automatically display "clicked". This, obviously, can be used when retrieving information from the server via AJAX requests and you don't have to rely on control IDs / CSS classes. They can change at any time, and your code is still relevant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With