Check out the MVVM structure. This is exactly what you need as your JavaScript becomes more complex. It shares your need for a relationship between your presentation code (html) and Presentation Logic (JavaSript)
Knockout.js is a really good library to get you started, I recommend going through tutorials so you can start with 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!'); } }
When a button is pressed, the div will automatically display โclickedโ. This can obviously be used when retrieving information from the server using AJAX requests, and you do not need to rely on ID / CSS classes. They can change at any time, and your code still matters.
Chris dixon
source share