Search code examples
javascriptbackbone.jsunderscore.jsunderscore.js-templating

Backbone View - Render event not firing


I have tried the other suggestions given by StackOverflow before raising this question.

Basically, this issue drives me crazy!! A simple code to render a view which is not firing at the first instance, however when I try to fire it through the Chrome DEV tools it fires!.. Code is given below,

<!DOCTYPE html>
<html>
	<head>
	<meta charset="utf-8">
	<title>JS Bin</title>
<script src="//jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>

	<script type="text/x-backbone" id="welcome-template">
		<h1>Welcome <%=userName%></h1>
	</script>
	<script>
		var User = Backbone.Model.extend({
			defaults: {
			  userName: 'Shanun',
			  userId: '232221',
			  userDept: 'IT'
			}
		});

		var user = new User();
	    
		var MyView = Backbone.View.extend({
			initialize: function(){
	        		this.render();
	      		},
			render: function(){
				var template = $("#welcome-template").html();
				var compiled = _.template(template, {userName: 'David'});
				this.$el.append(compiled);
			}
		});

		var myView = new MyView ({el: '#app', model: user});
		myView.render();
	  </script>
	  
	</head>
	<body>
		<div id="app"></div>
	</body>
</html>

Can some shed some light please?

Thanks, Dave


Solution

  • not fired? I would assume render is always fired but when script tag is processed for the first time app div is not rendered yet so it can't be appended.