Search code examples
javascriptbackbone.jsbackbone-views

Backbone View not loading


I apologise for what is probably an incredibly simple mistake, but my backbone view is not loading. The code works fine in this fiddle: http://jsfiddle.net/v9suvj3m/1/ however in my code it does not work. I assume I am making a mistake either where I include the scripts in the jade file, or am not waiting for something to load in the js? If I insert alerts, an alerts before defining myview triggers, but nothing after that.

Edited to take into account comments. Main issue still not fixed.

index.jade

doctype html
html(lang='en')
  head
    link(rel="stylesheet" type="text/css" href="styles/main.css")
    title Homepage

  body
    #body-js
    script(src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js")
    script(src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js")
    script(src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js")
    script(type='text/javascript' src='scripts/main.js')

scrips/main.js

var myview, view;

myview = Backbone.View.extend({
  initialize: function() {
  return $("#body-js").html("hello");
  }
});

view = new myview({
  el: '#body-js'
});

edit: Using the non minified version of backbone I see that the error is at if (protoProps && _.has(protoProps, 'constructor')) { - line 1538. I assume this means that _ is underfined. Is this a correct assumption, and how can I fix it?


Solution

  • Put your scripts after your #body-js.

    Backbone doesn't find the dom element to make its view.

    Because your code is executed before the dom is ready.

    Which is not the case on jsFiddle. It's executed onDomready.

    You also need to tabulate one more level right after the line html(lang='en').

    I've finally found your problem... Your underscore is way too old (1.1.6).

    Use the latest version (1.7.0).