Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i separate JavaScript View/Logic code properly [closed]

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)?

like image 276
user1703761 Avatar asked Sep 27 '12 15:09

user1703761


Video Answer


1 Answers

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.

like image 51
Chris Dixon Avatar answered Sep 21 '22 08:09

Chris Dixon