Monday, October 29, 2012

AngularJS: Write Less Code, Go Have Girlfriend Sooner

Programming is a craft that is notorious for not being too conducive for having a relationship. Aside from it having the stigma for being too geeky, it is notorious for siphoning all your precious time that could be otherwise spent on some important things in life, like being able to leave work on time and get the chance (before you can even get the chance, you have to get the time first) to date the girl you're dreaming of; or if you already are a family man, spend quality time with your family.


Let's look at sample code that could be shortened if we are using a good framework. First, the longer code:

http://jsfiddle.net/3Xtnd/

Countries <select id='TravelToCountryId'></select>
<br/>
Cities <select id='TravelToCityId'></select>​

...

$(function() { 
    
    // Models
    
    var countries = 
    [
        { 
            CountryId: 1, CountryName: 'Philippines',
            Cities :
            [
                { CityId: 1, CityName: 'Manila' },
                { CityId: 2, CityName: 'Makati' },
                { CityId: 3, CityName: 'Quezon' },            
            ]            
        },
        { 
            CountryId: 2, CountryName: 'Canada',
            Cities:
            [
                { CityId: 4, CityName: 'Toronto' },
                { CityId: 5, CityName: 'Alberta' },
                { CityId: 6, CityName: 'Winniepeg' },
            ]           
            
        },
        { 
            CountryId: 3, CountryName: 'China',
            Cities:
            [
                { CityId: 7, CityName: 'Beijing' },
                { CityId: 8, CityName: 'Shanghai' }
            ]           
        },    
    ];    
           
    
    // Controller that live two lives,
    // can't focus well on model :-)
    
    
    // Populate then wire event...
    
    var country = $('#TravelToCountryId');
    var city = $('#TravelToCityId');
    
    
    $.each(countries, function() {
        var option = $('<option />').val(this.CountryId).text(this.CountryName);
        country.append(option);
    });
    
    $(country).change(function() {
        filterCitiesByCountry();
    });
    
    // ...Populate then wire event
    
    
    // Init..
    var initialCountryId = countries[1].CountryId; 
    $(country).val(initialCountryId);
    filterCitiesByCountry();    
    // ...Init
    
    function filterCitiesByCountry() {
        var selectedCountryId = country.val();
        
        
        // filter works on all browsers, except <= IE8
        var countryObj = countries.filter(function(v) {
            return v.CountryId == selectedCountryId;
        })[0];
        

        var cities = countryObj.Cities;
                
        city.empty();
        
        $.each(cities, function() {
            var option = $('<option/>').val(this.CityId).text(this.CityName);
            
            city.append(option);
        });

        
    } // filterCitiesByCountry()
         
    
});      



Then let's use a framework that facilitates declarative programming and allows separation of concerns. Let's use an MVC framework for JavaScript, let's use AngularJS. Following is the equivalent AngularJS code, there's nothing in the code that deals directly with the UI. You'll notice that the code don't have anything that imperatively populates the HTML, most are done declaratively, thus making your code shorter. Barring HTML tags, jQuery approach took 88 lines of code, while AngularJS took 56 lines only. Lesser code, lesser to debug when something goes wrong, lesser time coding, lesser development time.

http://jsfiddle.net/nDw2Z/

<div ng-controller='TravelController' ng-init='init()'>
Countries 
    <select ng-model='TravelToCountryId'     
    ng-options='i.CountryId as i.CountryName for i in countries' 
    
    ng-init='filterCitiesByCountry()'
    ng-change='filterCitiesByCountry()'></select>
    
<br/>
Cities 
    <select ng-model='TravelToCityId'
    ng-options='i.CityId as i.CityName for i in citiesFromSelectedCountry'></select>
</div>

...

function TravelController($scope) {
    
    // Models
    
    $scope.countries = 
    [
        { 
            CountryId: 1, CountryName: 'Philippines',
            Cities :
            [
                { CityId: 1, CityName: 'Manila' },
                { CityId: 2, CityName: 'Makati' },
                { CityId: 3, CityName: 'Quezon' },            
            ]            
        },
        { 
            CountryId: 2, CountryName: 'Canada',
            Cities:
            [
                { CityId: 4, CityName: 'Toronto' },
                { CityId: 5, CityName: 'Alberta' },
                { CityId: 6, CityName: 'Winnipeg' },
            ]           
            
        },
        { 
            CountryId: 3, CountryName: 'China',
            Cities:
            [
                { CityId: 7, CityName: 'Beijing' },
                { CityId: 8, CityName: 'Shanghai' }
            ]           
        },    
    ];    
    
    $scope.TravelToCountryId = null;
    $scope.TravelToCityId = null;
    
    
    // Controller's actions
    
    $scope.init = function() {
        $scope.TravelToCountryId = $scope.countries[1].CountryId;    
    };
        
    
    $scope.filterCitiesByCountry = function() {
               
        var cities = $scope.citiesFromSelectedCountry = $scope.countries.filter(function(v){
            return v.CountryId == $scope.TravelToCountryId; 
        })[0].Cities;
        
        $scope.TravelToCityId = cities[0].CityId;                
        
    };
                
}

The user decided that the program could be more appealing and user-friendly by making the country selection done via radio button since there are only few of them to select from. This user requirement necessitates changing your code as the dropdown list and radio button have different mechanism to carry information; on dropdown list it comes from option tags, and on radio button it is directly on input's value attribute. Dropdown list's mechanism for setting the default value is a mere .val(valueHere), while radio button need to find the object and then set its checked attribute.


http://jsfiddle.net/KhANV/

Countries <div id='divTravelToCountryId'></div>
<br/>
Cities <select id='TravelToCityId'></select>​

...

$(function() { 
    
    // Models
    
    var countries = 
    [
        { 
            CountryId: 1, CountryName: 'Philippines',
            Cities :
            [
                { CityId: 1, CityName: 'Manila' },
                { CityId: 2, CityName: 'Makati' },
                { CityId: 3, CityName: 'Quezon' },            
            ]            
        },
        { 
            CountryId: 2, CountryName: 'Canada',
            Cities:
            [
                { CityId: 4, CityName: 'Toronto' },
                { CityId: 5, CityName: 'Alberta' },
                { CityId: 6, CityName: 'Winnipeg' },
            ]           
            
        },
        { 
            CountryId: 3, CountryName: 'China',
            Cities:
            [
                { CityId: 7, CityName: 'Beijing' },
                { CityId: 8, CityName: 'Shanghai' }
            ]           
        },    
    ];    
           
    
    
    // Controller that live two lives,
    // can't focus well on model :-)
    
    // Populate then wire event...
    
    var divCountry = $('#divTravelToCountryId');
    
        
    $.each(countries, function() {
        
        var option = $(
            '<input type="radio" ' + 
            ' id="TravelToCountryId"' + 
            ' name="TravelToCountryId" />').val(this.CountryId);
        
        divCountry.append(option).append(' ' + this.CountryName).append('<br/>');
        
    });
    
    var country = $('input[name=TravelToCountryId]');
    var city = $('#TravelToCityId');
    
    
    $(country).change(function() {     
        filterCitiesByCountry();
    });
    
    // ...Populate then wire event
    
    
    // Init...
    var initialCountryId = countries[1].CountryId;     
    $(country).filter('[value="' + initialCountryId + '"]').prop('checked',true);        
    filterCitiesByCountry();
    // ...Init
    
            
    function filterCitiesByCountry() {
                
        var selectedCountryId = $(country).filter(':checked').val();
                   
        
        // filter works on all browsers, except <= IE8
        var countryObj = countries.filter(function(v) {
            return v.CountryId == selectedCountryId;
        })[0];
        

        var cities = countryObj.Cities;
                
        city.empty();
        
        $.each(cities, function() {
            var option = $('<option/>').val(this.CityId).text(this.CityName);
            
            city.append(option);
        });
        
    }
       
});      
​

Now let's try it on AngularJS: http://jsfiddle.net/ZjehV/

<div ng-controller='TravelController' ng-init='init()'>

Countries     
    <div ng-repeat='i in countries'>
    <input type=radio ng-model='$parent.TravelToCountryId'  
    name='TravelToCountryId'        
    ng-init='filterCitiesByCountry()'
    ng-change='filterCitiesByCountry()' value='{{i.CountryId}}' />&nbsp;{{i.CountryName}}
    </div>    
        
<br/>
Cities <select id='TravelToCityId'
    ng-model='TravelToCityId'
    ng-options='i.CityId as i.CityName for i in citiesFromSelectedCountry'
    ></select>
    
</div>
​
...

function TravelController($scope) {
    
    // Models
    
    $scope.countries = 
    [
        { 
            CountryId: 1, CountryName: 'Philippines',
            Cities :
            [
                { CityId: 1, CityName: 'Manila' },
                { CityId: 2, CityName: 'Makati' },
                { CityId: 3, CityName: 'Quezon' },            
            ]            
        },
        { 
            CountryId: 2, CountryName: 'Canada',
            Cities:
            [
                { CityId: 4, CityName: 'Toronto' },
                { CityId: 5, CityName: 'Alberta' },
                { CityId: 6, CityName: 'Winnipeg' },
            ]           
            
        },
        { 
            CountryId: 3, CountryName: 'China',
            Cities:
            [
                { CityId: 7, CityName: 'Beijing' },
                { CityId: 8, CityName: 'Shanghai' }
            ]           
        },    
    ];    
    
    $scope.TravelToCountryId = null;
    $scope.TravelToCityId = null;
    
    
    // Controller's actions
    
    $scope.init = function() {
        $scope.TravelToCountryId = $scope.countries[1].CountryId;    
    };
        
    
    $scope.filterCitiesByCountry = function() {
               
        var cities = $scope.citiesFromSelectedCountry = $scope.countries.filter(function(v){
            return v.CountryId == $scope.TravelToCountryId; 
        })[0].Cities;
        
        $scope.TravelToCityId = cities[0].CityId;        
                
    };
            
}
​


Let's measure the level of effort that was spent between the two when you accomodate changes in user requirement. jQuery's lines of code have increased from 88 to 97, while AngularJS stays the same, 56. So what changed on those 56 lines? Zero, zilch, nada. When you come to think of it, even your user request another changes on your UI, be they wanted to select from ul+li, table+td, div+a and whatnot, there should be no changes on your code to make that happen. Your code should be able to reflect only how your business operates, it should be devoid of idiosyncrasies of whatever UI choice imposes.


As an exercise, please try to convert jQuery version to use radio buttons too for city selection. Here's the AngularJS changes: http://jsfiddle.net/DL74y/, it has no changes on code, only the tags were changed.


With AngularJS or any decent MVC framework for javascript, you'll be able to accomplish more with lesser amount of effort. With AngularJS, your code can work exclusively on how your business operates, it doesn't have to pay attention on how the UI will be presented and used. User interface is a very fickle business, and you don't want your code to be impacted too much whenever some change is requested.



A minor aside on AngularJS, you cannot directly use ng-model='TravelToCountryId' when it's inside an ng-repeat, as different TravelToCountryId will be allocated on each element repetition, think of variable inside a loop. To prevent that from happening, make sure to reference the parent scope of TravelToCountryId, you can do that by prefixing the variable name with $parent.



The actual slogan of AngularJS: Write less code, go have beer sooner.

Sunday, October 28, 2012

jQuery filter, promotes DRY principle

You have this:

<input type='radio' name='TravelToCountryId' value='PH'> Philippines
<input type='radio' name='TravelToCountryId' value='CA'> Canada
<input type='radio' name='TravelToCountryId' value='ZH'> China​​​​​​​​

...

var country = $('input[name=TravelToCountryId]');
    
$(country).change(function() {     
    alert($(this).val());
});





You want to set the default(say Canada) using this:

$('input[name=TravelToCountryId][value=CA]').prop('checked',true);


Though that works, but as an astute developer you are, you feel that you are violating DRY principle and noticed that you can re-use the country object.


To re-use, use filter function. filter and find functions are almost synonym, however don't confuse them, find is for getting the descendant elements of existing elements, filter is for getting the elements from existing elements based on filter.


Do this:

$(country).filter('[value=CA]').prop('checked',true);​

Tuesday, October 9, 2012

Set focus on input upon click on ng-repeat

Live test: http://jsfiddle.net/epAxT/5/


Model and Controller:

function TestController($scope) {
        
    // Models
    $scope.messages = 
    [
    { Message: 'Life is what happens to you...', By: 'John Lennon' },
    { Message: 'If you can\'t explain...', By: 'Albert Einstein' },
    { Message: 'The answer to life...', By: 'Douglas Adams' }
    ];
    
    
    $scope.currentMessage = null;
    
    // Controller's actions
    
    $scope.setCurrentMessage = function(msg) {
        $scope.currentMessage = msg;
    };

    $scope.isCurrentMessage = function(msg) {
        return msg == $scope.currentMessage;
    };
    
    $scope.addMessage = function() {
        var msg = {Message: 'blah', By: 'Anonymous'};
        $scope.currentMessage = msg;
        $scope.messages.push(msg);
    };
    
}
    
    


    
    
var appGreat = angular.module('AppGreat', []);

appGreat.directive('toFocus', function ($timeout) {
    return function (scope, elem, attrs) {
        scope.$watch(attrs.toFocus, function (newval) {
            if (newval) {
                $timeout(function () {
                    elem[0].focus();
                }, 0, false);
            }
        });
    };
});
​


View:
<br/>
<div ng-app='AppGreat' ng-controller='TestController'>
    
    <table>
        <thead>
            <tr>
                <th>Message</th><th>By</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat='m in messages'>
                <td width='200px'>
                    <div ng-hide='isCurrentMessage(m)' 
                         ng-click='setCurrentMessage(m)'>
                        {{m.Message}}
                    </div>
                    <div ng-show='isCurrentMessage(m)'>
                        <input ng-model='m.Message'
                               to-focus='isCurrentMessage(m)'
                               style='width: 100%' />
                    </div>
                    
                    
                </td>
                
                <td>
                    <div ng-hide='isCurrentMessage(m)' 
                         ng-click='setCurrentMessage(m)'>
                        {{m.By}}
                    </div>
                    <div ng-show='isCurrentMessage(m)'>
                        <input ng-model='m.By'/>                        
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
    
    
    <input type='button' ng-click='addMessage()' value='Add Message'/>
    
</div>       ​

Friday, September 21, 2012

My first visualization of math

Following code rotates a triangle:

import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;
 
class Renderer implements GLEventListener 
{
    private GLU glu = new GLU();
 
    float  i = 0;
    
    public void display(GLAutoDrawable gLDrawable) 
    {
        i += 0.05f;
        
        final GL2 gl = gLDrawable.getGL().getGL2();
        
        
        gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
        gl.glLoadIdentity();
        
        
        gl.glTranslatef(0f, 0.0f, -6.0f);
        
        
        double rotCos = Math.cos(i);
        double rotSine = Math.sin(i);
          
          
          
        gl.glBegin(GL2.GL_TRIANGLES);       

        {
            double pointX = 0;
            double pointY = 1.0f; 
            double pointZ = 0f;
            
            double pointNewX = pointX * rotCos + pointY * rotSine;
            double pointNewY = -(pointX * rotSine) + pointY * rotCos;
            double pointNewZ = 0;
            
                    
            gl.glVertex3d(pointNewX , pointNewY , pointNewZ);   
        }
        
 
        
        {
            double pointX = -1f;
            double pointY = -1f;
            double pointZ = 0f;
            
            double pointNewX = pointX * rotCos + pointY * rotSine;
            double pointNewY = -(pointX * rotSine) + pointY * rotCos;
            double pointNewZ = 0;
            
            gl.glVertex3d(pointNewX , pointNewY , pointNewZ);       
        }
       
        
        
        
        {
            double pointX = 1f;
            double pointY = -1f;
            double pointZ = 0f;
            
            double pointNewX = pointX * rotCos + pointY * rotSine;
            double pointNewY = -(pointX * rotSine) + pointY * rotCos;
            double pointNewZ = 0;
            
            gl.glVertex3d(pointNewX , pointNewY , pointNewZ);       
        }
       
        
        
        gl.glEnd();
        
        

    }
 
 
    public void displayChanged(GLAutoDrawable gLDrawable, boolean modeChanged, boolean deviceChanged) 
    {
        System.out.println("displayChanged called");
    }
 
    public void init(GLAutoDrawable gLDrawable) 
    {
        System.out.println("init() called");
        GL2 gl = gLDrawable.getGL().getGL2();
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        gl.glShadeModel(GL2.GL_FLAT);
    }
 
    public void reshape(GLAutoDrawable gLDrawable, int x, int y, int width, int height) 
    {
        
        System.out.println("reshape() called: x = "+x+", y = "+y+", width = "+width+", height = "+height);
        final GL2 gl = gLDrawable.getGL().getGL2();
 
        if (height <= 0) // avoid a divide by zero error!
        {
            height = 1;
        }
 
        final float h = (float) width / (float) height;
 
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity();
        glu.gluPerspective(45.0f, h, 1.0, 20.0);
        gl.glMatrixMode(GL2.GL_MODELVIEW);
        gl.glLoadIdentity();
    }
 
 
    public void dispose(GLAutoDrawable arg0) 
    {
        System.out.println("dispose() called");
    }
}


Finally made sense of those bracketed expressions, thanks Wikipedia!

http://en.wikipedia.org/wiki/Rotation_(mathematics)

Saturday, August 25, 2012

Is AngularJS very easy that there are very few blogs documenting it?

This app demonstrates how easy it is to structure your model with AngularJS and the UI automatically follow what happens to model seamlessly.

Live demo: http://jsfiddle.net/bpvjL/6/


HTML:

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">


    <ul class="unstyled">
      <li ng-repeat="todo in todos" >       
          <span class="isactive-{{activeTodo == todo}}" ng-click="changeActive(todo)" >
              <a href="#" style="none">{{todo.text}}</a>
          </span>
      </li>
    </ul>
      
      

    <form ng-submit="addTodo()">
      <input type="text" ng-model="todoText"  size="30"
             placeholder="add new todo here">
      <input class="btn-primary" type="submit" value="add">
    </form>
          
      <ul>
      <li ng-repeat="step in activeTodo.steps">
          {{$index + 1}} {{step.text}}
      </li>   
      </ul>

    <form ng-submit="addStep()">
      <input type="text" ng-model="stepText"  size="30"
             placeholder="add new step to: {{activeTodo.text}}">
      <input class="btn-primary" type="submit" value="add">
    </form>
          
  </div>
</div>
​


Javascript:

function TodoCtrl($scope) {
  $scope.todos = [
    {text:'learn angular',
     steps : [
         { text : 'learn' },
         { text : 'to' },           
         { text : 'build' }                    
     ]},
    {text:'build an angular app',
     steps : [ 
         { text : 'build' },         
         { text : 'and' }, 
         { text : 'they' }, 
         { text : 'will' }, 
         { text : 'come' }
     ]}
  ];
    
  $scope.activeTodo = $scope.todos[0];
  

  $scope.addTodo = function() {
        var todo = {text:$scope.todoText, steps: []};
        $scope.todos.push(todo);
        $scope.todoText = '';
        $scope.activeTodo = todo;
  };
    
  $scope.changeActive = function(active) {
        $scope.activeTodo = active;
  };


  $scope.addStep = function() {
        $scope.activeTodo.steps.push({text:$scope.stepText});
        $scope.stepText = '';
  };
    

}

​


CSS:

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<style>
.isactive-true {
    background: YELLOW;
}

Tuesday, August 7, 2012

jQuery selector nuances

​<select name="Beatle" id="Beatle"​​​​​​​​​​​​​​​​​​​​​​​>
    <option id=9>John</option>
    <option id=8>Paul</option>
    <option id=7 selected>George</option>
    <option id=6>Ringo</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​


<script>
 var selectedText = "";

 selectedText = $('#Beatle').text();
 alert('Not Correct: ' + selectedText);

 selectedText = $('option:selected','#Beatle').text();
 alert('Correct: ' + selectedText);

 selectedText = $('#Beatle:selected').text();
 alert('Not correct: ' + selectedText);

 selectedText = $('#Beatle :selected').text();
  alert('Correct: ' + selectedText);

});
</script>


Live test: http://jsfiddle.net/5XAYh/

Monday, August 6, 2012

Manual model and view synchronization with JavaScript

When you don't use an MVC javascript framework that can do two-way databinding, you are left on your own to synchronize the state between the model and the view.


Live test: http://jsfiddle.net/E7F7D/33/

<table id='dataHere' border='1'>
<thead>
    <!-- ID presence on HTML is optional --> 
    <!--<th style='visibility: collapse'>Id</th>-->
    
    <th>Lastname</th><th>Firstname</th><th>Asset</th><th>Actions</th>
</thead>
<tbody>
</tbody>
    
    
</table>

<hr/>

    <input type="button" id="viaModel" value="test via model"/>

    <input type="button" id="viaDom" value="test via DOM"/>
        
    <div id="debugLog">
     </div>


<script>
    var people = [
        { Id: 1, Lastname: 'Lennon', Firstname: 'John', Asset: 40090.1296 },
        { Id: 2, Lastname: 'McCartney', Firstname: 'Paul', Asset: 38000.34 },
        { Id: 3, Lastname: 'Harrison', Firstname: 'George', Asset: 37000.56 },
        { Id: 4, Lastname: 'Starr', Firstname: 'Ringo', Asset: 40000.78 },
        
        { Id: 5, Lastname: 'Buendia', Firstname: 'Ely', Asset: 40000.93 },
        { Id: 6, Lastname: 'Marasigan', Firstname: 'Raymund', Asset: 39000.12 },
        { Id: 7, Lastname: 'Zabala', Firstname: 'Buddy', Asset: 39000.13 },
        { Id: 8, Lastname: 'Adoro', Firstname: 'Marcus', Asset: 39000.14344 }    
        
        ];
    
    
    var tbl = $('#dataHere');
    
    $('#viaModel').click(function() {
        var dl = $('#debugLog');
        dl.html('Model-based approach. Data are in their pristine state');
        $.each(people, function() {
            var person = this;
            
            dl.append(person.Id + '-->' + person.Lastname + ', ' + person.Firstname + ': ' + this.Asset + '<p/>');
        });
    });
    
    $('#viaDom').click(function() {
        try {
            var dl = $('#debugLog');
            var tbl = $('#dataHere');
    
            dl.html('Using DOM approach for stashing and extracting data, the Id won\'t be available unless we stash it on HTML');
            
            
    
            var trs = $('tbody > tr', tbl);
    
    
            $.each(trs, function() {
                var tr = this;
                var tds = $('td', tr);
        
                // Alas! ID won't be available if you didn't put it in td tag or whatnot.
                // If we use DOM approach for stashing our data, 
                // we have to stash ID on the HTML itself, 
                // this is called Smart UI approach, this is abhored, 
                // as the code is tightly coupled to UI/presentation layer.
                
        
                var tdLastname = $(tds[0]);
                var tdFirstname = $(tds[1]);                       
                var tdAsset = $(tds[2]);
                
                
                
                var lastname = tdLastname.text();
                var firstname = tdFirstname.text();
                // another problem with Smart UI approach is the data gets mangled
                
                var asset = tdAsset.text().replace('Php ','').replace(',','');
                
                dl.append(lastname + ', '+ firstname + ': ' + asset);                
                
                
            })
                
            dl.append('And data gets mangled and truncated too. Check the rounding-offs');
        
        } catch(e) {
            alert(e);
        }
                       
    });
    
    
    $.each(people, function() {
        var person = this;
        
        var trPerson = $('<tr/>');
    
        
        // optional
        // var tdId = $('<td/>').css('visibility','collapse');
        
        var tdLastname = $('<td/>');
        var tdFirstname = $('<td/>');
        var tdAsset = $('<td/>');
        var tdActions = $('<td/>');
        
        var aEditAction = $('<a/>').prop('href','#').text('Edit');
        var aDeleteAction = $('<a/>').prop('href','#').text('Delete');
        
       
        // optional
        // tdId.text(this.Id);
        
        tdLastname.text(this.Lastname);
        tdFirstname.text(this.Firstname);
        tdAsset.text(formatMoney(this.Asset, 2, 'Php ', ',','.'));
    
        
        aEditAction.click(function() {
            // alert('Will edit ' + person.Id + ' ' + person.Lastname);
            
            
            var ln = prompt('Enter value', person.Lastname);
            person.Lastname = ln == null ? person.Lastname : ln;
            
            tdLastname.text(person.Lastname);
        });        
        
     
        
        aDeleteAction.click(function() {
            if (confirm('Will delete ' + person.Id + ' ' + person.Lastname)) {   
                
                people.splice(people.indexOf(person),1);
                
                trPerson.remove();
            }
        });
        
            
    
        
        trPerson
            // .append(tdId) // optional
            .append(tdLastname).append(tdFirstname)
            .append(tdAsset).append(tdActions);
        
        tdActions.append(aEditAction).append('|').append(aDeleteAction);
    
      
          
        tbl.append(trPerson);
    
            
    });
    
     // alert(8);
        // alert(formatMoney(92334.55, 2,'Php ',',','.'));
        
    // http://www.josscrowcroft.com/2011/code/format-unformat-money-currency-javascript/
    function formatMoney(number, places, symbol, thousand, decimal) {
        number = number || 0;
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : "$";
        thousand = thousand || ",";
        decimal = decimal || ".";
        var negative = number < 0 ? "-" : "",
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }
</script>