How do i separate JavaScript View/Logic code properly

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 eg:

$.("<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)?


在你的情况下,我可以推荐你看看Knockoutjs,AngularJS或Backbone.js。


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.


To render html you can use Handlerbars.js it is very mature and have lots of documentation

For event binding I recommend you to use jQuery delegate on the parent object that don't had deleted with the ajax update. This way you only need to reassign events on every request

链接地址: http://www.djcxy.com/p/64234.html

上一篇: 描述符:通过属性访问的优先级

下一篇: 如何正确分离JavaScript视图/逻辑代码