Friday, 4 March 2016

NodeJS and MySql with KnockoutJS - Part I

NodeJS ?


NodeJS is Server side platform built on Google Chrome Javascript Engine. NodeJS performs like server side language in Web Developments. Paypal also using NodeJS for Back-end developments. Previously Javascripts used only on Front End Developments. But now Javascript use for Both Back-end and Front-end developments. (Source: NodeJS Tutorials)




Knockout?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model (Source: KnockoutJS Official Website). KnockoutJS use MVVM approach and developers can bind data retrieve from back-end to DOM elements.


Data View Application with NodeJS and MySql with KnockoutJS.

Normally AngularJS and Knockout functionalities are same. But these 2 frameworks used different framework approaches. Inter-connectivity between Angular and NodeJS is easy. Basically NodeJS provide API for connect with front-end. In this development process,

  1. User Load Page, request will send to NodeJS Server.
  2. From routine mechanism on Node Server, Server will return HTML page.
  3. During this load Ajax Request will send to NodeJS server for retrieve data.
  4. NodeJS will retrieve data from Mysql Database and convert data to JSON object and send it to front-end.
  5. Knockout Library will read json object sent by server and bind data to page.

Development

you can check project on GitHub (https://github.com/kitcodes/knockout-node-1)

I used public folder for css, js and image components. server folder for business logic and view folder for view data on html pages.

Mysql

I created Database (db_blog) with tbl_blog (b_id (int, primary key), b_title (varchar100), b_date (date), b_desc (varchar200))

NodeJS

Dependency NodeJS components. (Install these components using npm)

  1. fs
  2. express
  3. jsonfile
  4. body-parser
  5. node-mysql
I used different js file for Mysql Connection and Data Retrieve (db.js) with OOP concepts on Javascript. for routine and data sending to front end i used different js file and it will act as a controller (index.js).

KnockoutJS

In view folder index.html has view for Front-End user. From knockout view model data will bind to dom tree. 


var data = []; var viewModel = {
blogs: ko.observableArray(data),
b_id: ko.observable(0),
}; ko.applyBindings(viewModel);

we have to bind html selectors with knockout. I have added list view for view data. 

<ul data-bind="template: { foreach: blogs }"> <li>
<div>
<a data-toggle="modal" data-bind="click:viewPopupModel" data-target="#myModal">
<span data-bind="text: b_title, value:b_id"></span>
</a>
</div>
</li>
</ul>


then data will be loaded to dom tree from Ajax request.

$(function(){
$.ajax({
url: "http://localhost:5000/viewall",
type: "GET"
}).then(function(data, err) {
console.log(data);
viewModel.blogs(data);
});
})







2 comments: