Wednesday, January 8, 2014

After Ajax, This is a good pattern to make hmtl using javascirpt

Today i thought how to devide roles of html and jascript.

I learned Angular Js and this is awesome but
to use it is too hard for me ..

so i have find different way and very easy.
find sprintf and try to use it

below are sample i made

Usually i use this pattern  but hard to read
Basic pattern

<!DOCTYPE html>
<html>
<head>    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id='frame'>
</div>
<script>
//ajax 파싱후 값을 가져왔다는 가정하에
    var obj = [{user_seq : 'user_seq1', user_name : "홍길동", age : '22'},
        {user_seq : 'user_seq2', user_name : "심청이", age : '19'},
{user_seq : 'user_seq3', user_name : "홍두깨", age : '30'}];

    var i=0;
    var str='';
    for(i=0; i<obj.length;i ++){
       str = str + '<div class="user" id="'+obj[i].user_seq+'1">'+
               '<div class="name">'+obj[i].user_name +'</div>' +
               '<div class="age">'+obj[i].age +'</div>';
    }
    document.getElementById('frame').innerHTML = str;
</script>
</body>
</html>

and changed some what different

Good pattern I think

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="sprintf.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id='frame'>
    <div class="user" id="%1s">
        <div class="name">%2s</div>
        <div class="age">%3s</div>
    </div>
</div>
<script>

    //ajax 파싱후
    var obj = [{user_seq : 'user_seq1', user_name : "홍길동", age : '22'},
        {user_seq : 'user_seq2', user_name : "심청이", age : '19'},
{user_seq : 'user_seq3', user_name : "홍두깨", age : '30'}];

    var i=0;
    var str ='';
    var content = document.getElementById('frame').innerHTML;;
    for(i=0; i<obj.length;i ++){

        str = str + sprintf(content,
obj[i].user_seq, //1 
obj[i].user_name, //2
obj[i].age); //3
    }

    document.getElementById('frame').innerHTML = str;

</script>
</body>
</html>

No comments:

Post a Comment