backbone error while trying to reset a collection - javascript

I am doing a very simple Backbone app example and I keep getting a JS error message. I basically have two files:
app.js
This file creates a Backbone.js app the appends a span from a template using data from a collection view to an already created div on the html file.
/*Backbone.js Appointments App*/
App = (function($){
//Create Appointment Model
var Appointment = Backbone.Model.extend({});
//Create Appointments Collection
var Appointments = Backbone.Collection.extend({
model: Appointment
});
//Instantiate Appointments Collection
var appointmentList = new Appointments();
appointmentList.reset(
[{startDate: '2013-01-11', title: 'First Appointment', description: 'None', id: 1},
{startDate: '2013-02-21', title: 'Second Appointment', description: 'None', id: 2},
{startDate: '2013-02-26', title: 'Third Appointment', description: 'None', id: 3}
]
);
//Create Appointment View
var AppointmentView = Backbone.View.extend({
template: _.template(
'<span class="appointment" title="<%= description %>">' +
' <span class="title"><%= title %></span>' +
' <span class="delete">X</span>' +
'</span>'
),
initialize: function(options) {
this.container = $('#container');
},
render: function() {
$(this.el).html(this.template(this.model));
this.container.append(this.el);
return this;
}
});
var self = {};
self.start = function(){
new AppointmentView({collection: appointmentList}).render();
};
return self;
});
$(function(){
new App(jQuery).start();
});
index.html
This file just calls the jquery, backbone and other js libraries and also created the div container where the Backbone.js app from the previous file will append the data.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>hello-backbonejs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script src="app.js" type="text/javascript"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
The error I get is the following:
Uncaught TypeError: Object [object Object] has no method 'reset' app.js:14
App app.js:14
(anonymous function) app.js:49
e.resolveWith jquery.min.js:16
e.extend.ready jquery.min.js:16
c.addEventListener.z jquery.min.js:16

You use Backbone 0.3.3 but Collection.reset was introduced in Backbone 0.5. See the changelog for more information.
Either upgrade Backbone (0.9.9 at the moment) (and Underscore and jQuery while you're at it) or use Collection#refresh if you absolutely have to keep Backbone 0.3.3 (but you will probably trip other errors down the road).

Related

View not initializing in Backbone.js

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

Uncaught ReferenceError: characters is not defined

I am creating a simple rest api in javascript, I want upon initialization, the widget must display a list of all characters.
here is folder structure :
├───book
└───book.js
├───store
│ └───store.js
here is my store.js
window.Store = {
create: function() {
var self = {};
var props = {
name: 'string',
species: 'string',
picture: 'string',
description: 'string'
};
var listProps = ['name', 'species'];
var detailProps = ['name', 'species', 'picture', 'description'];
var characters = [
{
id: makeID(),
name: 'Ndiefi',
species: 'Wookie',
picture: 'store/img/ndiefi.png',
description: 'A legendary Wookiee warrior and Han Solo’s co-pilot aboard the Millennium Falcon, Chewbacca was part of a core group of Rebels who restored freedom to the galaxy. Known for his short temper and accuracy with a bowcaster, Chewie also has a big heart -- and is unwavering in his loyalty to his friends. He has stuck with Han through years of turmoil that have changed both the galaxy and their lives.',
_delay: 500
},
];
}
}
here is index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character Book</title>
<!-- 3rd party vendor libraries -->
<link rel="stylesheet" href="vendor/font-awesome-4.6.3/css/font-awesome.min.css">
<script src="vendor/jquery-3.1.0.min.js"></script>
<script src="vendor/underscore-1.8.3.min.js"></script>
<!-- 1st party internal libraries -->
<script src="store/store.js"></script>
<script src="tests/start-test.js"></script>
<script src="tests/test-book.js"></script>
<!-- The source of the 'Book' widget -->
<link href="book/book.css" rel="stylesheet">
<script src="book/book.js"></script>
<script>
$(function() {
var frame = $('#test-frame');
var run = $('#test-run');
var results = $('#test-results');
var store = Store.create();
run.click(function() {
run.prop('disabled', true).text('Running Tests');
results.removeClass('test-pass test-fail').text('');
testBook(frame).then(
function success() {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-pass').text('All tests passed');
},
function failure(err) {
run.prop('disabled', false).text('Run Tests');
results.addClass('test-fail').text('Test failed, see console');
}
);
});
Book.init(frame, store);
});
</script>
</head>
<body>
<button id="test-run">Run Tests</button>
<span id="test-results"></span>
<div id="test-frame">
</div>
</body>
</html>
here is what I have tried :
books.js
var data = JSON.parse(characters);
data.forEach(characters => {
console.log(characters.name)
});
so when I run the app in my browser I see the following error :
Uncaught ReferenceError: characters is not defined
what is wrong with my code ? any suggestion or help will be helpfull thanks

Backbone script to read from external JSON

I want to display data from JSON using a backbone script.
This is the html Page:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="backbone.js"></script>
<script src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'document.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
initialize: function(){
this.listenTo(this.collection,"add", this.renderItem);
},
render: function () {
this.collection.each(function(model){
var profileTemplate = this.template(model.toJSON());
this.$el.append(profileTemplate);
}, this);
return this;
},
renderItem: function(profile) {
var profileTemplate = this.template(profile.toJSON());
this.$el.append(profileTemplate);
}
});
var profileList = new ProfileList();
var profilesView = new ProfileView({ collection: profileList });
profilesView.render();
});
</script>
</head>
<body>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="name">
<%= name %>
</div>
<div class="title">
<%= title %>
</div>
<div class="background">
<%= background %>
</div>
</div>
</div>
<br />
</script>
</body>
</html>
This is my json data:
document.json
[
{
"id": "p1",
"name" : "AAAA",
"title" : "BBBB",
"background" : "CCCC"
},
{
"id": "p2",
"name" : "DDDD",
"title" : "EEEE",
"background" : "FFFF"
},
{
"id": "p3",
"name" : "GGGG",
"title" : "HHHH",
"background" : "IIII"
}
]
There's nothing being displayed on the page.
Am I missing something?
I have been trying to get the JSON data printed on the div element in specified HTML. But Nothing being displayed. I tried debugging the code, I could insert alert statement before Backbone.Model.extend inside document.ready in jquery. But when I put alert statement inside it, it isnt coming up. So, the code inside Backbone.Model.extend must be gone wrong somewhere.
Somebody help me?
You need to check the order of loading your scripts, jquery should come first, underscore secondly (since you are using undescore.js templating) then backbone:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
If that doesn't solve your problem then you could either try sending in a static reference to your initial set of data, then call fetch() as needed to grab more, or you can call fetch explicitly as follows:
var profileList = new ProfileList();
var profilesView = new ProfileView({collection: profileList});
profileList.fetch();
profileList.bind('reset', function () {
profilesView.render();
});
Working Demo
You should load scripts in order, jquery, underscore and then Backbone

backbone.js Can't find error in script

I'm new to javascript and backbone.js
I want to create simple web page with 10 squares with form that will take square id and color.
So every square must have its own style in CSS.
I tried to make it with 10 templates. But script doesn't work at all.
Here is my code:
alert("script entry");
$(function () {
blocks = [
{number: "1", state: "block1" },
{number: "2", state: "block2" },
{number: "3", state: "block3" },
{number: "4", state: "block4" },
{number: "5", state: "block5" },
{number: "6", state: "block6" },
{number: "7", state: "block7" },
{number: "8", state: "block8" },
{number: "9", state: "block9" },
{number: "10", state: "block10" },
];
var BlockModel = Backbone.Model.extend({
defaults:{
"state": "block1",
"number": "1"
}
});
var BlockCollection = Backbone.Collection.extend({
model: BlockModel,
});
var blockNumbers = new BlockCollection([
model:BlockModel
]);
var BlockView = Backbone.View.extend({
tagName: "blockTag",
className: "blockClass",
templates: {
"block1": _.template($('#block1').html()),
"block2": _.template($('#block2').html()),
"block3": _.template($('#block3').html()),
"block4": _.template($('#block4').html()),
"block5": _.template($('#block5').html()),
"block6": _.template($('#block6').html()),
"block7": _.template($('#block7').html()),
"block8": _.template($('#block8').html()),
"block9": _.template($('#block9').html()),
"block10": _.template($('#block10').html())
},
render: function () {
var state= this.model.get("state");
var tmpl = this.templates(state);
$(this.el).html(tmpl(this.model.toJSON()));
return this;
}
});
var appView = Backbone.View.extend({
el: $("#block"), //большой контейнер
initialize: function(){
this.collection = new blockNumbers(blocks);
this.render();
},
render: function(){
_.each(this.collection.models, function () {
that.renderBlock(this.model);
}, this);
},
renderBlock: function (inputModel) {
var blockView = new BlockView({
{model: inputModel}
});
this.$el.append(blockView.render().el);
}
});
var app = new appView();
});
Where is my error?
My index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TEST</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="block">
<script type="text/template" id="block1">
<div class="block1"><%=number%></div>
<div class="buttonplace">
<input type="button" value="check" />
</div>
</script>
<script type="text/template" id="block2">
<div class="block2"><%=number%></div>
</script>
<script type="text/template" id="block3">
<div class="block3">3</div>
</script>
<script type="text/template" id="block4">
<div class="block4">4</div>
</script>
<script type="text/template" id="block5">
<div class="block5">5</div>
</script>
<script type="text/template" id="block6">
<div class="block6">6</div>
</script>
<script type="text/template" id="block7">
<div class="block7">7</div>
</script>
<script type="text/template" id="block8">
<div class="block8">8</div>
</script>
<script type="text/template" id="block9">
<div class="block9">9</div>
</script>
<script type="text/template" id="block10">
<div class="block10">10</div>
</script>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
There are several problems with your code, primarily you are using parentheses in some cases instead of brackets [ and instead of curly braces {. You also have some extra trailing commas. Further in your HTML your closing tag for the block div should be before all your script templates.
For example
var blockNumbers = new BlockCollection([
model:BlockModel
]);
Should be
var blockNumbers = new BlockCollection({
model:BlockModel
});
And
var tmpl = this.templates(state);
Should be
var tmpl = this.templates[state];
In addition in your appView you are trying to instantiate a new instance of your instance
this.collection = new blockNumbers(blocks);
While you probably meant to do
this.collection = new BlockNumbers(blocks);
Here's a working jsBin
Aside from all that you have a lot of repetition with your templates, you can really consolidate them all into one or two templates.
For example you can just have one template for blocks with a button and one for blocks without a button and update the blocks state accordingly
<script type="text/template" id="blockWithButton">
<div class="block<%=number%>"><%=number%></div>
<div class="buttonplace">
<input type="button" value="check" />
</div>
</script>
<script type="text/template" id="blockWithoutButton">
<div class="block<%=number%>"><%=number%></div>
</script>
Another jsbin
templates: {
"block1": _.template($('#block1').html()),
...
"block10": _.template($('#block10').html())
},
you have defined an object above.
var tmpl = this.templates(state);
but you call it as a function.
you may get the templates as this.templates[state];
UPDATE
I think you can just use the same template as:
<script type="text/template" id="block">
<div class="block<%=number%>"><%=number%></div>
<div class="buttonplace">
<input type="button" value="check" />
</div>
</script>
and you can simplfy your model like this, too.
Of course, if you need.
UPDATE
You may new a Collection with some options out of single {} but not [] or more {}s, like this:
var blockNumbers = new BlockCollection({
model:BlockModel
});
...
var blockView = new BlockView({
model: inputModel
});
not:
var blockNumbers = new BlockCollection([
model:BlockModel
]);
...
var blockView = new BlockView({
{model: inputModel}
});
UPDATE
the blockNumbers is an instance of Collection, you can't fetch data for it by new like:
this.collection = new blockNumbers(blocks);
You should assign the bolckNumbers to this.collection, and give it an url , then call sync() or fetch() to get the data, then render it.
END
Lastly, I have found too much mistake of basics above, Backbone.js is simple but hard, you ought to be able to solve it yourself, it is useful to you.
Thanks.

Hello World - Backbone + Firebase + Backfire

I'm trying to create a simple hello world with backbone and firebase(using backfire). The code is working to insert data to firebase, but when I try to get data and fill the template, it says "Uncaught ReferenceError: firstName is not defined". On debug I can see the object with the data but I don't know how to provide the template with this object.
Here is the code:
$(document).ready(function(){
var registerModel = Backbone.Model.extend({
defaults: {
firstName: '',
lastName: ''
}
});
var registerColletion = Backbone.Firebase.Collection.extend({
model:registerModel,
firebase: new Firebase("https://XXXXXXXX.firebaseio.com/")
});
var registerView = Backbone.View.extend({
el: $("#myTest"),
itemTemplate: _.template($('#item-template').html()),
events: {
"click #btnSave": "saveToFirebase"
},
initialize: function () {
this.listenTo(registerList, 'add', this.render);
},
render: function(){
$('#divContent').html(this.itemTemplate(this.model.toJSON()));
},
saveToFirebase: function () {
registerList.add({firstName: $("#txtFirstName").val(), lastName: $("#txtLastName").val()});
}
});
var registerList = new registerColletion;
var app = new registerView({model:registerList});
});
The exact point of the exception is on render function:
render: function(){
$('#divContent').html(this.itemTemplate(this.model.toJSON()));
},
The template:
<script type="text/template" id="item-template">
<div class="view">
<p>
<%- firstName %> <%- lastName %>
</p>
</div>
</script>
Can anyone please help me? I think I'm missing something (probably obvious) but I can't see it.
Thank you!
When you create the registerView you're telling it that the underlying model is a registerList (not a registerModel)
var app = new registerView({model:registerList});
Therefore, when the render function is called, it's looking for the firstName property of a registerList, and that property doesn't exist.
Seems like you've got Models and Collections mixed up

Categories

Resources