eomeroff
eomeroff

Reputation: 9925

Backbone with underscore template example

I am new to backbonejs and underscorejs. I found some video materials on to watch and I faced problem when tried to modify example.

Here is my code:

<html>
<head >
    <meta charset="UTF-8">  
    <script type="text/javascript" src="javascript/jQuery.js"></script>
    <script type="text/javascript" src="javascript/underscore.js"></script>
    <script type="text/javascript" src="javascript/backbone.js"></script>

    <script type="text/template" id="list-template">
      <li><a href="<%= href %>"><%= text %></a></li>
    </script>

    <script type="text/javascript">


        model = new Backbone.Model({
            data: [
                {text: "Google", href: "google.com"},
                {text: "Facebook", href: "facebook.com"},
                {text: "Yahoo", href: "yahoo.com"}
            ]
        });


        var View = Backbone.View.extend({
            el: "#container",
            events: {
                "click button": "render"
            },
            render: function(){
                var data = this.model.get('data');
                for(var i = 0; i<data.length; i++){
                    var variables = { href: data[i].href, text: data[i].text };
                    var li = _.template( $("#list-template").html(), variables );
                    this.$el.find('ul').append(li);
                }
            }
        });

        var view = new View({ model: model });

    </script>
</head>

<body>
    <div id="container">
        <button>Load</button>
        <ul id="list">
    </ul>
    </div>
</body>

It of course does not work and I am failing to find the cause. If you see please answer or guide on how to bind template on custom event rather then initialize.

Upvotes: 1

Views: 7350

Answers (1)

Lukas
Lukas

Reputation: 9845

The problem is that the JavaScript is executing before the elements have been rendered on the page. Wrap your code in $(document).ready():

$(document).ready(function() {
    var model = new Backbone.Model({
    ....
    var view = new View({ model: model });
});

Upvotes: 5

Related Questions