Ive created a simple backbone app that gets data from MySQL database about users to display in a view called LeaderBoardView. Below is the HTML code for the view,
<body>
<div id="container"></div>
<h1>Leaderboard</h1>
<table class="table" id="modtable">
<tr>
<th>Username</th>
<th>Level</th>
</tr>
</table>
<div id="bbcontent"></div>
Im trying to get data and populate inside the div with bbcontent as the id. Below is my Backbone model, collection and view,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-
min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js">
</script>
<script language="javascript">
$(document).ready(function() {
alert("heyyyyyy")
//model
var User = Backbone.Model.extend({
idAttribute: "userId",
defaults: {
username: null,
userLevel: null
}
});
//collection
var Users = Backbone.Collection.extend({
model: User,
url: "/CW2/ASSWDCW2/cw2app/index.php/Leaderboard/leaderboard",
});
var usersC = new Users();
var LeaderboardDeetsView = Backbone.View.extend({
model: usersC,
el: $('#bbcontent'),
intialize: function() {
alert("asndasnxdjksa")
usersC.fetch({
async: false
})
this.render()
},
render: function() {
var self = this;
usersC.each(function(c) {
var block = "<div class='name'><h1>" + c.get('username') + "</h1></div>"
self.$el.append(block)
})
}
})
var leaderboardDeetsView = new LeaderboardDeetsView();
});
Problem with this code : The LeaderboardDeetsView isn't being called hence the collection fetch function inside the initialize function of the LeaderboardDeetsView isn't being called.How can I correct my code? Please help
I see eleven issues with your code. The first two prevent your code from working as intended:
intializeinstead ofinitialize. The method will not run for this reason.initializemethod, you are attempting to fetch the users synchronously, in order to render them immediately. Alas, there is no such thing as a synchronous request, so your view will be rendering an empty collection. In good Backbone style, you need to listen for events so you know when is the right time to render:The next six issues are missed opportunities to follow best practices. These do not currently break your code, but they very well might in the future:
usersCas themodelofLeaderboardDeetsView, but it is a collection. Views have both amodeland acollectionproperty, so you should use each for its proper purpose.model(which should be thecollection) on the prototype. While this works in principle, you cannot use this mechanism to have multiple instances ofLeaderboardDeetsViewthat each present a different list of users (since they all share the same prototype). For this reason, theViewconstructor accepts an options object withmodelandcollectionproperties, so you can give each view its own unique model:;). JavaScript will let you get away with this most of the time, but not always. Train yourself to be strict with this and save yourself some unpleasant and confusing surprises down the line!fetchbelongs outside of the view.LeaderboardDeetsView, you set theelto an already resolved jQuery instance. It works fine in this case, but in the general case, the element with the given selector might not exist yet. Set theelto just a selector string instead, and the view will perform this lookup for you automatically when the view is constructed.rendermethod of a view should returnthisso you can continue chaining methods after it. The same is true of most other methods that do not already return some other value. Taking into account all issues so far, your code should now look like this:The last three issues are missed opportunities to benefit from the latest and greatest of the libraries that are available to you:
LeaderboardDeetsViewusing backbone-fractal, a small library that I wrote. Alternatively, you could use theCollectionViewfrom Marionette (but the syntax is different in that case). This makes your code more modular, easier to understand and easier to test and maintain.templatefunction from Underscore. If you want to take your templates more seriously, you can also use a dedicated templating library such as Handlebars or Wontache. Below, I demonstrate how Underscore's_.templatewould work for theUserViewfrom the previous point:Here is a final version of your code, with all of the above points implemented. Doesn't it look sleek, concise and modular?