I'm using the "rails-backbone" gem in my Rails 3.2 project. By this design my Backbone Views are loaded in the <head> tag. When using Routes everything works fine, but Views do not render if I try to use them directly without Routes. If I put the Views code in <body> everything works as expected.

Is there a way to make the Views work when defined in <head>?

Update: in <body>:

<script type="text/javascript">
    var lv = new ListView();
</script>

in javascript file included in <head>:

window.ListView = Backbone.View.extend({
    el: $("#node"), // This does not work
    initialize: function(){
        _.bindAll(this, 'render'); 
        this.el = $("#node"); // Works if I add this line
        this.render();
    },
    render: function(){
        $(this.el).append("<ul> <li>hello world</li> </ul>");
    }
});

As I understand it #node does not exist yet, which is why it is not bound to el. I don't quite understands when happens here: var lv = new ListView(), I thought I was creating an instance from a Class (I guess I'm getting a clone of an Object?). Is there another way of making the code work by modifying the code in <body> instead of the included javascript?

2 Answers

0
Derick Bailey On Best Solutions

Your problem is caused by using a jQuery selector as the value for el in the view.

Read this:

http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/

0
JayC On

if you want something to work in the head, but after the DOM is ready, (And apparently since you're using jQuery) just set up your views in the DOMReady event via:

$(document).ready(function(){ 
   ...
   //set up view here
   ...
 });