How do I properly separate JavaScript view / logic code

I get JSON objects from a website with checkboxes update / create / delete. Based on this information, I either update, create, or delete HTML elements and bind callbacks. This may affect several HTML elements.

My current approach was to put everything in concrete objects that handle HTML generation via jquery, for example:

$.("<table>").addChild($("<tr>")).addClass('test') 

and bind event listeners. But with the addition of more code, it has become really messy, and now it is looking for a suitable way to split the code.

Any ideas on how to do this correctly? Wireframes? Maybe jQuery templates (which still leave me in the dark, how to add callbacks)?

+7
source share
5 answers

In your case, I can recommend you look at Knockoutjs , AngularJS or Backbone.js .

0
source

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!'); } } // Bind viewmodel 

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.

+4
source

For html rendering you can use Handlerbars.js , it is very mature and has a lot of documentation

To bind events, I recommend that you use a jQuery delegate for the parent that was not deleted when ajax was updated. Thus, you only need to reassign events for each request

0
source

Check out Backbone.js . This is a very popular and flexible MVC-ish configured for JS browser applications. The code is posted on github .

0
source

JS knockout may be worth it to look like, it separates the data model from the presentation model and takes care of the dependencies between them.

0
source

All Articles