Cannot get models to display attributes - javascript

I would like to know why this is not displaying the entries I created. I am struggling to find good simple tutorials that use Marionette so I took the angry cats tutorial found here (http://davidsulc.com/blog/2012/04/15/a-simple-backbone-marionette-tutorial/) and tried to make something similar but even simpler so I could understand what is going on better. Any help would be appreciated.
Here is the Javascript, I am using Marionette.js
MyApp = new Backbone.Marionette.Application();
MyApp.addRegions({
listBox : "#listBox"
});
Entry = Backbone.Model.extend({
defaults: {
entry : "Blank"
},
});
EntryList = Backbone.Collection.extend({
model: Entry
});
EntryView = Backbone.Marionette.ItemView.extend({
template: "entry-template",
tagName: 'tr',
className: 'entry'
});
EntriesView = Backbone.Marionette.CompositeView.extend({
tagName: "table",
template: "#entries-template",
itemView: EntryView,
appendHtml: function(collectionView, itemView){
collectionView.$("tbody").append(itemView.el);
}
});
MyApp.addInitializer(function(options){
var entriesView = new EntriesView({
collection: options.ents
});
MyApp.listBox.show(entriesView);
});
$(document).ready(function(){
var ents = new EntryList([
new Entry({ entry: 'abc' }),
new Entry({ entry: 'def' }),
new Entry({ entry: 'ghi' })
]);
MyApp.start({entry: ents});
});
Here is the html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Simple Demo</title>
<link rel="stylesheet" href="assets/screen.css">
</head>
<body>
<div id = "listBox">
</div>
<script type="text/template" id="entries-template">
<thead>
<tr class='header'>
<th>Entry</th>
</tr>
</thead>
<tbody>
</tbody>
</script>
<script type="text/template" id="entry-template">
<td><%- entry %></td>
<td><button class="delete">Delete</button></td>
</script>
<script src="js/lib/jquery.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<script src="js/lib/backbone.marionette.js"></script>
<script src="js/demo.js"></script>
</body>
</html>

It seems you're not using the right key in your options. You should have:
var entriesView = new EntriesView({
collection: options.entry
});
As a side note, my "angry cats" tutorial is a bit dated. To learn the basics about using Marionette views, you'll be better off reading this free pdf: http://samples.leanpub.com/marionette-gentle-introduction-sample.pdf (it's the free sample to my Marionette book)
In addition your template selector isn't valid: you need to have "#entry-template" where you have "entry-template".

Related

Difference between el and tagname in backbone

I am learning Backbone and I am not able to understand the difference between el and tagname. I looked into this BackboneJs: In a view whats the difference between el: and tagName: . But I could not understand.
Below is what I have till now.
Script Example:
// Vehicle Model
var Vehicle = Backbone.Model.extend(
{
idAttribute: "registrationNumber",
urlRoot: "/api/vehicles",
validate: function(attrs)
{
if(!attrs.registrationNumber)
return "Vehicle without reistration";
}
});
// Vehicle Collection
var Vehicles = Backbone.Collection.extend(
{
model: Vehicle
});
// Vehicle View
var VehicleView = Backbone.View.extend(
{
tagName: "li",
//*******************************************************
// el: "li" **THIS DOES NOT WORK!!
//**********************************************************
render: function ()
{
var source = $("#vehicleTemplate").html();
var template = _.template(source);
this.$el.html(template(this.model.toJSON()));
return this;
}
});
// Vehicle View for collection
var VehiclesView = Backbone.View.extend({
render: function() {
var self = this;
this.collection.each(function(vehicle) {
var vehicleView = new VehicleView({
model: vehicle
});
self.$el.append(vehicleView.render().$el);
});
}
});
// creating collection
var vehicles = new Vehicles(
[
new Vehicle({registrationNumber: "ABCD1234"}),
new Vehicle({registrationNumber: "ABCD5678"}),
new Vehicle({registrationNumber: "DCBA1234"}),
new Vehicle({registrationNumber: "DCBA1423"})
]);
// instance for vehicles View
var vehiclesView = new VehiclesView({collection: vehicles, el: "#vehicleAnchor"});
vehiclesView.render();
Index.html
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.min.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/styles.css">
<script src="js/lib/modernizr-2.6.2.min.js"></script>
</head>
<body>
<ul id = "vehicleAnchor">
</ul>
<script src="js/lib/jquery-min.js"></script>
<script src="js/lib/underscore-min.js"></script>
<script src="js/lib/backbone-min.js"></script>
<script id = "vehicleTemplate" type = "text/html">
<%= registrationNumber%>
</script>
<script src="js/main.js"></script>
</body>
</html>
Everything is working fine but when I replace tagName with el, it stops working Why please guide me in layman language.
According to the documentation (http://backbonejs.org/#View-el), the el property is used as a reference to the DOM element, whereas the tagName is used when creating an element.
This means that when you specify a string as the el it will look in the existing DOM tree (basically your HTML) for an element that matches that selector (it will function as a jquery selector). Since you do not have an li element in your markup, the el will be null and the view will be unable to initialize.
When you are using the tagName on the other hand, backbone automatically uses that to create a new element and assign it to the el property.
Be aware however, that the newly created element must then be added to the DOM. This is what you do in VehiclesView with the line self.$el.append(vehicleView.render().$el);

Backbone.js: Clicking U.I list elements to show them in a different section of the page

I am working on a project in Backbone.js were I get the results from a Food API and then display them. I have this piece of functionality working. The next piece of functionality I need is to be able to click an item from the results list and be able to save that result, showing it in the foods tracked list on the right side of the page. The foods tracked list would show the information about the Food (Food Name, Brand and Calories) as well as a total amount of calories from all the foods tracked. I am having trouble creating this functionality because I do not know how to click a list item and have it take the item information in the html list element and place it in another part of the page.
Here is my JSfiddle link- https://jsfiddle.net/Tiquismiquis/2nLezvmg/3/
Here is my JAVASCRIPT-
$(function(){
var SearchList = Backbone.Collection.extend({
initialize: function(){
this.bind("reset", function(model, options){
console.log("Inside event");
console.log(model);
});
},
//** 1. Function "parse" is a Backbone function to parse the response properly
parse:function(response){
//** return the array inside response, when returning the array
//** we left to Backone populate this collection
return response.hits;
}
});
// The main view of the application
var App = Backbone.View.extend({
el: 'body',
events: {
"input #searchBox" : "prepCollection",
"click li" : "track"
},
initialize: function () {
this.model = new SearchList();
this.prepCollection =_.debounce(this.prepCollection, 1000);
this.$list = $('#listing');
// this.saved =$('#tracked');
},
prepCollection: function(){
var name = $('input').val();
var newUrl = "https://api.nutritionix.com/v1_1/search/" + name + "?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name,brand_name,item_id,nf_calories&appId=26952a04&appKey=private_key";
if (name == ""){
this.$list.html("")
}
else{
this.model.url = newUrl;
this.model.fetch({
success: function (response, xhr) {
console.log("Inside success");
console.log(response.toJSON());
},
error: function (errorResponse) {
console.log(errorResponse)
}
});
this.listenTo(this.model, 'sync', this.render);
}
},
// track: function(){
// },
render: function(){
var terms = this.model;
var wordhtml = "";
terms.each(function (term) {
wordhtml = wordhtml + "<li>" +"<strong>" + term.get('fields')["item_name"] + '</strong>'+ ' ('+ term.get('fields')["brand_name"] + ')'+' - '+ term.get('fields')["nf_calories"] + ' Calories' + "</li>"
}, this);
this.$list.html(wordhtml);
}
});
var app = new App();
});
Here is my HTML-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Food Guide App</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-6">
<h1>Interactive Food Guide</h1>
<input type="text" id="searchBox"> <br/><br/>
<ul id="listing"></ul>
</div>
<div class="col-xs-6">
<h1>Foods Tracked</h1>
<ul id="tracked"></ul>
<p id="total">total calories: <span>0</span></p>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Backbone and Underscore -->
<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.1/backbone-min.js"></script>
<!-- apps functionality -->
<script src="js/app.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
There are many ways to do it - through a backbone listView or simply by adding data-* attributes to the element.
Below is an example demonstrating the latter :
Template change :
var liTemplate = '<li data-brand="<%-data.brand_name%>" data-name="<%-data.item_name%>"><strong><%-data.item_name%> (<%-data.brand_name%>)</strong></li>';
wordhtml = _.template(liTemplate)({ data : term.get('fields')});
View change :
events:{
'click li': 'track'
},
track: function(e){
var $target = $(e.currentTarget);
var itemName = $target.attr('data-name');
var brandName = $target.attr('data-brand');
//do whatever you need
}
Find the working fiddle at https://jsfiddle.net/nitincool4urchat/2nLezvmg/8/

Backbonejs not showing this.options parsed from router

for some reason itemDetails is not parsing the .options in the MenuItemDetails view.
This is the javascript code:
// ROUTER
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
"menu-items/new": "itemForm",
"menu-items/:item": "itemDetails"
},
list: function(){
$('#app').html('List screen');
},
itemDetails: function(item){
var view = new MenuItemDetails (
{
name: item,
category: 'Entree',
imagepath: 'no-image.jpg'
}
);
$('#app').html(view.render().el);
},
itemForm: function(){
$('#app').html('New item form');
}
});
// VIEWS
var MenuItemDetails = Backbone.View.extend({
render: function(){
var markup = '<div>' +
'<h1>'+this.options.name+'</h1>' +
'</div>';
this.$el.html(markup);
return this;
}
});
var app = new AppRouter();
$(function() {
Backbone.history.start();
});
The html code is:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jashkenas.github.io/underscore/underscore-min.js"></script>
<script src="http://jashkenas.github.io/backbone/backbone-min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script src="js/views/menuitemdetails.js"></script>
<script src="js/app.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Off the Backbone</h1>
<ul class="nav nav-pills">
<li>Food</li>
<li>Add Item</li>
<li>Garden Salad</li>
</ul>
<div class="container" id="app">
</div>
</div>
</body>
</html>
As you can see, the two first links are doing well but the third one is getting an error which tells that the parameters in itemDetails are not parsed to the view. Please help me with this one here.
Your router works fine. It's the way in which your passing the data from the router into the view that's broken. Here is a working jsfiddle: http://jsfiddle.net/somethingkindawierd/rEa88/
Relevant changes are defining the model
var MenuItemModel = Backbone.Model.extend();
and then passing it into the view
var view = new MenuItemDetails ({
model: new MenuItemModel({
name: item,
category: 'Entree',
imagepath: 'no-image.jpg'
})
});
then using the model when rendering
'<h1>'+this.model.get('name')+'</h1>'
Your router seems confusing :
"menu-items/new": "itemForm",
"menu-items/:item": "itemDetails"
According to this mapping, both of the following will link will map to the itemDetails method :
<li>Add Item</li>
<li>Garden Salad</li>
The correct way is to change your router to handle only one route like so :
"menu-items/:item": "wrapper"
and handle the logic correctly in wrapper :
wrapper: function(item){
if(item === 'new'){
//handle new
} else {
//handle everything else
}
HTH!

Simplest of backbone.js examples

I'm creating a bare bones backbone example to try to learn it and am having issues getting my view to render. I've based it on Thomas Davis's tutorial but looked at many of the other apps and tutorials available.
I'm changing Davis's tutorial not only because I want to add an input box, but also because based on the backbone docs I thought it needed less code and a different structure. Obviously because I can't get this to work, I don't know what's needed and what isn't.
My ultimate goal was to just add the names in li tags within ul#friends-list, although I don't think el: 'body' will help me there.
What am I doing wrong? Thanks for any help.
My html:
<!DOCTYPE HTML>
<html>
<head>
<title>Tut</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
</head>
<body>
<input type="text" placeholder="Enter friend's name" id="input" />
<button id="add-input">Add Friend</button>
<ul id="friends-list">
</ul>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
My test.js
$(function() {
Friend = Backbone.Model.extend();
//Create my model
var friends = new Friend([ {name: 'Eddard Stark'}, {name: 'Robert Baratheon'} ]);
//Create new models to be used as examples
FriendList = Backbone.Collection.extend({
model: Friend
});
//Create my collection
var friendslist = new FriendList;
//Created to hold my friends model
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getFriend',
},
initialize: function() {
_.bindAll(this, 'render');
},
getFriend: function() {
var friend_name = $('#input').val();
var friend_model = new Friend({name: friend_name});
},
render: function() {
console.log('rendered')
},
});
var view = new FriendView({el: 'body'});
});
You had some fundamental problems with your code to get the functionality that you required. I turned your code into a jsfiddle and you can see the working solution here.
http://jsfiddle.net/thomas/Yqk5A/
Code
<!DOCTYPE HTML>
<html>
<head>
<title>Tut</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
</head>
<body>
<input type="text" placeholder="Enter friend's name" id="input" />
<button id="add-input">Add Friend</button>
<ul id="friends-list">
</ul>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getFriend',
},
initialize: function() {
var thisView = this;
this.friendslist = new FriendList;
_.bindAll(this, 'render');
this.friendslist.bind("add", function( model ){
alert("hey");
thisView.render( model );
})
},
getFriend: function() {
var friend_name = $('#input').val();
this.friendslist.add( {name: friend_name} );
},
render: function( model ) {
$("#friends-list").append("<li>"+ model.get("name")+"</li>");
console.log('rendered')
},
});
var view = new FriendView({el: 'body'});
});
I noticed that you wanted as little code as possible so I left some things out that you don't need such as declaring an actual model. It might be easier if you use a collection like in the example instead.
Also I have just launched a new site containing Backbone tutorials which might help solve your problem.
BackboneTutorials.com

Event binding with views and AJAX-loaded collections

I'm starting out with Backbone.JS, and have a question about how this should work.
I have a page which should load a list of sports, and then render the view. Now, because the list of sports is loaded via AJAX, I need to bind events to the collection so that it's only rendered when the data from that collection is actually loaded.
Here's what I've got so far:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="../../src/vendor/zepto.js" type="text/javascript" charset="utf-8"></script>
<script src="../../src/vendor/underscore.js" type="text/javascript" charset="utf-8"></script>
<script src="../../src/vendor/backbone.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="sportsList"></div>
<script type="text/template" id="sports-template">
<ul>
<% _.each(sports, function(sport){ %>
<li>
<%= sport.getDescription() %>
</li>
<% }); %>
</ul>
</script>
<script type="text/javascript" charset="utf-8" src="application.js"></script>
</body>
</html>
As for the javascript code:
var Sport = Backbone.Model.extend({
getDescription: function() {
return this.get('description');
}
});
var Sports = Backbone.Collection.extend({
model: Sport,
initialize: function(options) {
this.bind("refresh", function() {
options.view.render();
});
var sports = this;
$.ajax({
url: 'http://localhost:8080/?service=ListSportsService&callback=?',
dataType: 'jsonp',
success: function(data) {
sports.refresh(data);
}
});
}
});
var SportsView = Backbone.View.extend({
el: '#sportsList',
template: _.template($('#sports-template').html()),
initialize: function() {
this.model = new Sports({view: this});
},
render: function() {
$(this.el).html(this.template({sports: this.model.models}));
return this;
}
});
var SportsController = Backbone.Controller.extend({
routes: {
'sports': 'listSports'
},
listSports: function() {
new SportsView();
}
});
$(document).ready(function(){
window.app = new SportsController();
Backbone.history.start();
});
The part that really nags me is having to pass the view to the collection and binding the refresh event there so that I can render the view once everything is loaded.
My question is, is there a DRYer/simpler way of doing this that I'm missing?
Keep in mind I'm using ZeptoJS instead of jQuery.
Your collection should read
var Sports = Backbone.Collection.extend({
model: Sport,
url: '/?service=ListSportsService&callback=?'
});
Always use Backbone.sync functionality when possible (here by specifying the url on the collection and using fetch).
Your controller should read
var SportsController = Backbone.Controller.extend({
routes: {
'sports': 'listSports'
},
listSports: function() {
//create the view with the collection as a model
this.sports = new Sports();
this.view = new SportsView({model: this.sports});
this.sports.bind("refresh", this.view.render);
// fetch all the sports
this.sports.fetch();
}
});
Enjoy.

Categories

Resources