Backbone js - View

List link

by Ruchi Samdariya

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.0/css/bootstrap-combined.min.css">
<div id="container" class="container well">
<button class="btn">Load</button>
<ul id="list"></ul>
</div>

<div id="listtemplate">
    <li><a href=""></a></li>    
</div>

CSS

#listtemplate{
 display:none;   
}

JavaScript

model = new Backbone.Model({
    data:[
        {text:'Google',href:'https://www.google.co.id'},
        {text:'Facebook',href:'https://www.facebook.com'},
        {text:'Twitter',href:'https://www.twitter.com'},
        {text:'Youtube',href:'https://www.youtube.com'}        
    ]
});

var View = Backbone.View.extend({
    initialize:function(){
       //console.log(this.options.blankOption); 
       //memanggil blankOption
        this.template = $('#listtemplate').children();
    },
    el:$('#container'),
    events:{
    //'eventName selectorName':'functionName' -->that will call 
       'click button':'render'        
    },
    render: function(){
        var data = this.model.get('data');
        for(var i=0, a = data.length ; i<a; i++){
           var li =this.template.clone().find('a').attr('href',data[i].href).text(data[i].text).end();
            this.el.find('ul').append(li);
        }            
    }    
    //if you use el:'#container' call with this.$el or $(this.el)
});

//var view = new View({blankOption:"iki isine blankoptions mas"});
//var view = new View({el:document.getElementById('container') });
//or var view = new View({el:$('#container') });
//var view = new View({tagName,className,id,attributes });
//property that you can use
var view = new View({model:model});
//el is DOM element