Backbone script to read from external JSON - javascript

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

Related

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.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.

backbone error while trying to reset a collection

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).

how to add columns to Kendo Grid that is filled with remote data?

So I have this view
<!DOCTYPE html>
<html>
<head >
<link href="<%: Url.Content("~/Content/kendo/2012.3.1114/kendo.common.min.css")%>" rel="stylesheet" type="text/css" />
<link href="<%: Url.Content("~/Content/kendo/2012.3.1114/kendo.default.min.css")%>" rel="stylesheet" type="text/css" />
<title><%: ViewBag.GestionTitle %></title>
</head>
<body>
<h1><%: ViewBag.GestionTitle %></h1>
<div id="usuariosGrid"></div>
<button id="addUsuario" type="button" class="k-input"><%: ViewBag.Agregar %></button>
<script src="<%: Url.Content("~/Scripts/jquery-1.7.1.min.js")%>"></script>
<script src="<%: Url.Content("~/Scripts/kendo/2012.3.1114/kendo.web.min.js")%>"></script>
<script src="<%: Url.Content("~/Scripts/usuario/usuario.js")%>"></script>
</body>
</html>
The div usuariosGrid is filled with remote data with the following function:
$(function () {
var ds = new kendo.data.DataSource({
transport: {
read: {
url: "http://127.0.0.1:81/SismosService.svc/usuario/index",
dataType: "json"
}
},
schema: {
data: "Response"
},
});
$("#usuariosGrid").kendoGrid({
columns: ["UsuarioId", "Nombre", "ApellidoP", "ApellidoM"],
dataSource: ds
});
});
This creates a grid with the columns specified in the function. Now what I want to do is for every row inserted also to add a column with two hyperlinks, one that would redirect me to an Edit page and another one that would redirect me to a Delete page.
How can I do this? I've looked for examples but haven't been able to find anything that resembles what I'm trying to achieve. Any help will be appreciated.
Basically you have to add a column to the columns definition of your kendoGrid. This new cell will contain the links (or even some buttons).
For this you would probably be interested on using columns.template field where you can merge HTML with variable data, for example, data from row that you editing or deleting.
Instead of a link you might define a custom action by doing something like:
columns : [
...
{ command: { text: "Edit", click: editRecord }, title: " ", width: "140px" }
]
and in editRecord you can do whatever you want (see KendoUI example here).

populate combobox with java script

i am write some code for cascading drop down with dojo ajax first drop down is static and second one is fetch the data from servlet .. i am using the dijit.form.ComboBox for make dropdown. Dojo provide the Store property in which he store the data and then put it into combobox. in servlet i through the array list to ajax function .. in ajax function i separate the array with comma and strore in variable and then store in the dojo's store property But i am not able to populate the whole string .. it populate only the last value of the string i am using following code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="dojo/dijit/themes/claro/document.css">
<link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css" />
<script src='dojo/dojo/dojo.js' data-dojo-config=' parseOnLoad: true'></script>
<script>
require(["dojo/parser", "dijit/form/ComboBox","dijit/form/TextBox"]);
function abc(){
var j = document.getElementById('state').value
dojo.xhrPost({
// The URL to request
url: "populate", //servlet name
timeout : 3000 ,
content: {
username: dojo.byId("state").value
},
load: function(result) { // the value in result is like=[Abas Store, Accounts ]
require([
"dojo/ready", "dojo/store/Memory", "dijit/form/ComboBox"
], function(ready, Memory, ComboBox){
var ss=result.split(",");
var i;
for (i=1;i< ss.length ;i++){
var stateStore = new Memory({
data: [ {name:ss[i], id: ss[i]} ]
});
}
ready(function(){
var comboBox = new ComboBox({
id: "stateSelect",
name:"select",
value: "Select",
store: stateStore,
searchAttr: "name"
}, "stateSelect");
});
});
}
});
}
</script>
</head>
<body class="claro">
<select data-dojo-type="dijit.form.ComboBox" id="state" name="state" onchange="abc();">
<option selected >Andaman Nicobar</option>
<option>Andhra Pradesh</option>
<option>Tripura</option>
<option>Uttar Pradesh</option>
<option>Uttaranchal</option>
<option>West Bengal</option>
</select>
<input id="stateSelect" >
</select>
</body>
</html>
please give me solution .. to populate all the value in combobox which is i get from array list
You are building the store in the for loop. Instead, you should build the data array that gets passed into the MemoryStore constructor.
require(["dojo/store/Memory", "dijit/form/ComboBox", "dojo/ready"],
function(Memory, ComboBox, ready){
ready(function) {
dojo.connect(dijit.byId('state'), 'onChange', function() {
var stateSelect = dijit.byId('stateSelect');
if (!stateSelect) {
stateSelect = new ComboBox({
id: "stateSelect",
name: "select",
value: "Select...",
searchAttr: "name"
}, "stateSelect");
}
var ss = 'Abas Store, Accounts';
ss = ss.split(',');
var data = [];
dojo.forEach(ss, function(item, idx) {
data.push({
id: idx,
name: item
});
stateSelect.set('store', new Memory({data: data}));
}); // dojo.connect
}); // ready
}); // require
​
The working example is at http://jsfiddle.net/cswing/DLNNc/

Categories

Resources