1

I am testing backbone.js using Backbone.js Wine Cellar Tutorial — Part 1: Getting Started with Spring MVC 3 and JSP. Because JSP has its own <%= %> I declared the following in main.js for using Mustache style marker.

_.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g
};

I changed the given HTML page accordingly to .jsp page for it to work properly. But I get the following error when I run the application.

enter image description here

Following is "index.html-changed-to-index.jsp" page.

<%@ include file="/WEB-INF/views/include.jspf" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cellar</title>
<%--Stylesheets --%>
<link href="<c:url value="/resources/css/styles.css" />" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header"><span class="title">Backbone Cellar</span></div>

<div id="sidebar"></div>

<div id="content">
<h2>Welcome to Backbone Cellar</h2>
<p>
This is a sample application part of of three-part tutorial showing how to build a CRUD application with Backbone.js.
</p>
</div>

<!-- Templates -->
<script type="text/template" id="tpl-wine-list-item">
    <a href='#wines/{{ id }}'>{{ name }}</a>
</script>

<script type="text/template" id="tpl-wine-details">
    <div class="form-left-col">
        <label>Id:</label>
        <input type="text" id="wineId" name="id" value="{{ id }}" disabled />
        <label>Name:</label>
        <input type="text" id="name" name="name" value="{{ name }}" required/>
        <label>Grapes:</label>
        <input type="text" id="grapes" name="grapes" value="{{ grapes }}"/>
        <label>Country:</label>
        <input type="text" id="country" name="country" value="{{ country }}"/>
        <label>Region:</label>
        <input type="text" id="region" name="region"  value="{{ region }}"/>
        <label>Year:</label>
        <input type="text" id="year" name="year"  value="{{ year }}"/>
    </div>
    <div class="form-right-col">
        <img height="300" src="<c:url value='/resources/images/{{ picture }}' />" />
        <label>Notes:</label>
        <textarea id="description" name="description">{{ description }}</textarea>
    </div>
</script>

<%--JavaScripts --%>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.7.1.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/underscore.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/backbone.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/main.js" />"></script>
</body>
</html>

Could someone help me understand why am I getting this error?

Thanks.

EDIT:

main.js

// Using Mustache style markers
_.templateSettings = {
        interpolate : /\{\{(.+?)\}\}/g
};

// Models
window.Wine = Backbone.Model.extend();

window.WineCollection = Backbone.Collection.extend({
    model:Wine,
    url:"/mavenedge/wines"
});


//Views
window.WineListView = Backbone.View.extend({

    tagName:'ul',

    initialize:function () {
        this.model.bind("reset", this.render, this);
    },

    render:function (eventName) {
        _.each(this.model.models, function (wine) {
            $(this.el).append(new WineListItemView({model:wine}).render().el);
        }, this);
        return this;
    }

});


window.WineListItemView = Backbone.View.extend({

    tagName:"li",

    template:_.template($('#tpl-wine-list-item').html()),

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }

});

window.WineView = Backbone.View.extend({

    template:_.template($('#tpl-wine-details').html()),

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }

});


// Router
var AppRouter = Backbone.Router.extend({

    routes:{
        "":"list",
        "wines/:id":"wineDetails"
    },

    list:function () {
        this.wineList = new WineCollection();
        this.wineListView = new WineListView({model:this.wineList});
        this.wineList.fetch();
        $('#sidebar').html(this.wineListView.render().el);
    },

    wineDetails:function (id) {
        this.wine = this.wineList.get(id);
        this.wineView = new WineView({model:this.wine});
        $('#content').html(this.wineView.render().el);
    }
});

var app = new AppRouter();
Backbone.history.start();

json returned from server enter image description here

skip
  • 12,193
  • 32
  • 113
  • 153
  • 1
    @MДΓΓБДLL & BalusC: Image has been changed. – skip Mar 20 '12 at 19:13
  • 2
    Too much noise in this question, I'm sure you can create a simpler code example that still reproduces the error. Any how I think the error is that you are _feeding_ the template with a _hash_ that **has not _id_ attribute**. – fguillen Mar 20 '12 at 19:23
  • Can you show what data your feeding in? Try adding a model manually (not pulling it from the server or using a route). – Jack Mar 20 '12 at 20:34
  • @Jack: I've made an edit to the question showing the `main.js` being used to declare components used to make the example work with the data being returned from the server. I think fguillen might be right though. – skip Mar 20 '12 at 21:22

3 Answers3

1

I'm pretty sure the problem is the data your getting (try inspecting the data you are fetching before you create the model, also note the case of the fields), using the code you posted i added a couple of lines to manually create a model and add it and it seems to render fine, make sure that you have are getting a value for all of the fields defined in your template (as @ fguillen mentioned most likely your missing the id field).

http://jsfiddle.net/khfCr/

Edit: Sorry I couldn't see the screen shot that you posted of the json returned, it looks correct. The problem is still probably the data being passed to the template, most likely your collection/models are not being initialized correctly.

Edit2: I updated the fiddle to manually create the list instead of pulling it from the server and the example works fine, examine your collection before you render it to see if it has been created correctly)

http://jsfiddle.net/khfCr/1/

Jack
  • 10,943
  • 13
  • 50
  • 65
  • I am wondering if the `id` attribute could be used on `.jsp` pages with ` – skip Mar 21 '12 at 00:13
  • 1
    I'm not sure I understand what you mean by possibly not being able to use the id attribute, the fact that the page is a .jsp page shouldn't make a difference to backbone.js. Anyway there are a couple of questions here on stackoverflow about resources for backbone.js here's one http://stackoverflow.com/questions/6349164/backbone-js-tutorials-and-learning-resources and here's a second one http://stackoverflow.com/questions/8782704/backbone-js-tutorial. Good Luck. – Jack Mar 21 '12 at 01:55
  • Just like you said the problem probably was the format of JSON being passed to the template. Also, just like you said, templating could be done on `.jsp` pages as well. I needed to parse the response in the collection by `parse: function(data) { return data.wines; }` to make it work. I am sending a simple example of it as an answer. Thanks. – skip Mar 22 '12 at 20:19
1

cellar.jsp

<%@ include file="/WEB-INF/views/include.jspf" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Welcome to Backbone Wine Cellar</title>

    <%--Templates --%>
    <script type="text/template" id="tpl-wine-list-item">
        <a href="#">{{ name }}</a>
    </script>
</head>
<body>

    <%-- Javascript --%>
    <script type="text/javascript" src="<c:url value="/resources/js/jquery-1.7.1.js" />"></script>
    <script type="text/javascript" src="<c:url value="/resources/js/underscore.js" />"></script>
    <script type="text/javascript" src="<c:url value="/resources/js/backbone.js" />"></script>
    <script type="text/javascript" src="<c:url value="/resources/js/cellar.js" />"></script>
</body>
</html>

celler.js

//for using 'Mustache.js' style templating 
_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

(function(){
    var Wine = Backbone.Model.extend();

    var WineList = Backbone.Collection.extend({
        model: Wine,
        url: "/mavenedge/wines",
        parse: function(data) {
            return data.wines;
        }
    });

    var WineListView = Backbone.View.extend({
        el: $("body"),
        template: _.template($("#tpl-wine-list-item").html()),
        initialize: function() {
            _.bindAll(this, "render");
            this.collection = new WineList();
            this.collection.fetch();
            this.collection.bind("reset", this.render); //'reset' event fires when the collection has finished receiving data from the server
        },
        render: function() {    
            _.each(
                        this.collection.models, 
                        function(wine) {
                            $(this.el).append(this.template({name: wine.get("name")}));
                        },
                        this
                    );
        }
    });

    var wineListView = new WineListView();
})();

Returns

enter image description here

skip
  • 12,193
  • 32
  • 113
  • 153
0

It looks like maybe you haven't passed an object with an id property into your template() call like this :

this.template( {id:100, name:"Gareth"});
Typo Johnson
  • 5,974
  • 6
  • 29
  • 40
  • 1
    Debug it at the point it's running the template to ascertain if the model.toJSON() is a wine object, this will rule out the rest of the code you've posted (or focus it). Also I'd pass in a collection to your wine list view eg; this.wineListView = new WineListView({collection:this.wineList});. _.each() might not be working – Typo Johnson Mar 20 '12 at 22:59