Backbone.js and jQuery Mobile with template

March 29th, 2012 by admin Leave a reply »

I have been doing a lot of research in my spare time with Javascript apps and I feel like I have a decent understanding of the Backbone.js framework and I recently tried to give it a front end using the jQuery Mobile framework.  Well, that turned out to be quite the challenge to get it to render it to the browser the way it was supposed to look.  Take the Backbone.js View below for instance:

var CommentsTable = Backbone.View.extend({
        el: $("#comments"),

        initialize : function(){
            _.bindAll(this, 'refreshed', 'addRow', 'deleted');
            this.template =  _.template($("#entry-template").html());
            Comments.bind("reset", this.refreshed);
            Comments.bind("add", this.addRow);
            Comments.bind("remove", this.deleted);

        // Prepends an entry row
        addRow : function(comment){
            var view = new EntryView({model: comment});
            var rendered = view.render().el;

        // Renders all comments into the table
        refreshed : function(){
            // reset the table
            $("#comments").html("<ul class='ui-listview ui-listview-inset ui-corner-all ui-shadow' id='commentList' data-role='listview' data-inset= 'true'></ul>");
            if(Comments.length > 0){
                // add each element

        // A comment has been deleted, so we rerender the table,
        // because this update could also come from another user via the
        // _changes feed
        deleted : function(){


On line 22 you will notice that I have hard-coded the actual CSS styling for the jQuery Mobile listview, I have tried every sort of method I could think of to get this work and the only way I could get it to work was to actually put the listview in there with it’s styling, here is the template I am using as well:

<script type="text/template" id="entry-template">
            <div class="ui-btn-inner ui-li"><div class="ui-btn-text">
                <a href="#page1" data-transition="slide" class="ui-link-inherit">
            </div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span></div>

I have more hard-coded styling in there to make it work correctly. So far this is the only way I can get it work correctly, it totally goes against how its recommended but it is working for me. If you have any suggestions, I am completely open as I am just learning this stuff myself.


Leave a Reply