I trying to render all objects names from my json file /api/tables.json into ? <li>there</li>'s
var Table = Backbone.Model.extend({
defaults: {
name: 'table',
id: 1
}
});
var Tables = Backbone.Collection.extend({
model: Table,
url: 'api/table.json'
});
var TablesView = Backbone.View.extend({
el: '#mydiv',
template: _.template($("#table-template").html()),
initialize : function() {
this.coll = new Tables()
this.listenTo(this.coll, 'reset', this.render);
this.coll.fetch();
},
render : function() {
this.$el.html(this.template({ table: this.coll.toJSON() }));
return this;
}
});
This is my template in index.html :
<div id="mydiv"></div>
<script type="text/template" id="table-template">
<ul>
<% _.each(table, function(table) { %>
<li><%= table.name %></li>
<% }); %>
</ul>
</script>
data from json file:
[
{
"name": "Table 1",
"id": 1
},
{
"name": "Table 2",
"id": 2
},
{
"name": "Table 3",
"id": 3
},
{
"name": "Table 4",
"id": 4
}
]
Please help me.... I don't know where is fault or what is missing.
I highly recommend using Backbone.Marionette plugin, which supports rendering of lists out of the box. You don't have to write boilerplate code for it. Just use CollectionView or CompositeView with the collection given as constructor arguments and define an ItemView for them (li element)
Related
Hello guys i got a problem, i cant display my graph it will become like this
As u can see there i also print console log.Nothing error occur.
Below is my index.php
<!DOCTYPE html>
<html>
<head>
<title>Line</title>
</head>
<body>
<div class="chart-container">
<canvas id="line-chartcanvas"></canvas>
</div>
<script src="js/Chart.bundle.min.js"></script>
<script src="js/jquery.js"></script>
<script src="js/chartmain.js"></script>
</body>
</html>
My chartmain.js
$(function(){
$.ajax({
url:"http://localhost/Media/chart.php",
type: "GET",
success : function (data) {
var count = [];
var displayLink = [];
for(var i in data){
count.push ("Player" + data[i].count);
displayLink.push(data[i].displayLink);
}
var chartdata = {
labels: displayLink,
datasets : [
{
data: displayLink,
label : 'Score',
backgroundColor:
"#F1c40F"
}
]
};
var ctx =$("#line-chartcanvas");
var barGraph = new Chart(ctx,{
type: 'bar',
data: chartdata
});
console.log(data);
},
error : function (data) {
console.log(data);
},
});
});
My Json Array
[
{
"count": "3",
"displayLink": "www.bharian.com.my"
},
{
"count": "1",
"displayLink": "www.hmetro.com.my"
},
{
"count": "6",
"displayLink": "www.nst.com.my"
},
{
"count": "1",
"displayLink": "www.sinarharian.com.my"
},
{
"count": "1",
"displayLink": "www.utusan.com.my"
}
]
I think perhaps it cant read my data from JSON but in console log it read
Thanks for helping me, already found the answer, I cant get data from JSON but i can data from MySQL
I have just added jqTree to my ASP MVC app. I need to display a TreeView in my view:
#{
ViewBag.Title = "Tree";
}
<h2>#ViewBag.Title</h2>
<div id="tree1" data-url="/Home/Nodes"></div>
#section scripts {
<script language="javascript" type="text/javascript">
$(function () {
$('#tree1').tree();
});
</script>
}
My data is in a JSON file (~/App_Data/Roles.json):
{
"id": 1,
"label": "Role1",
"children": [
{
"id": 2,
"label": "Role2",
"children": [
{
"id": 3,
"label": "Role3",
"children": [
]
},
{
"id": 4,
"label": "Role4",
"children": [
]
}
]
}
]
}
How do I load the json file in the controller action method to display corresponding TreeView in the view?
public ActionResult Nodes()
{
var roles = // load json file
return Json(roles, JsonRequestBehavior.AllowGet);
}
You can pass the json from JSON file(~/App_Data/Roles.json) and create the tree in the following way:
Add the below code in your view:
<div id="tree1"></div>
#section scripts {
<script language="javascript" type="text/javascript">
$.ajax({
type: 'POST', // we are sending data so this is POST
traditional: true,
url: '/Home/Nodes', // controller/action name
success: function (d) {
$('#tree1').tree({
data: [jQuery.parseJSON(d)]
});
}
});
</script>
}
Create a Nodes() function in your HomeController as:
public ActionResult Nodes()
{
string roles = string.Empty;
using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Roles.json")))
{
roles = r.ReadToEnd();
}
return Json(roles, JsonRequestBehavior.AllowGet);
}
And you will be able to view your tree. Please let me know if you face any issues.
I have problems create in my backbone app link with two ids from json. Before I had in template simply variable id. My link was .../tables/ after click to table .../table:id/ But in table is next menu and I need after click to this menu ids from both array, like .../table:id/menu:id there will be showed category view....
My First Tables template
<script type="text/template" id="table-template">
<% _.each(tables, function(table) { %>
<li class="tableli" data-table_id="<%= table.get('id') %>">
<div class="obrazok"></div>
<%= table.get('name') %>
</li>
<% }); %>
</script>
First Tables view
var TablesView = Backbone.View.extend({
initialize:function () {
this.render();
},
tagName: "ul",
events: {
"click li.tableli" : "openMenuItem"
},
openMenuItem: function(e){
currentLink = $(e.currentTarget);
tableId = currentLink.data('table_id');
app.navigate("table" + tableId + "/menus", true);
console.log("table/" + tableId + "/menus");
},
render:function () {
var that = this;
var tables = new Tables();
tables.fetch({
success: function (tables) {
var template = _.template($('#table-template').html(), {tables: tables.models});
that.$el.html(template);
}
})
}
});
Ok After click to one of li I wanna have link like ...table:id/ and open only menus view
My menus view:
<script type="text/template" id="menu-template">
<% _.each(menus, function(menu) { %>
<li class="menucls" data-menu_id="<%= menu.get('id') %>">
<%= menu.get('name') %>
</li>
<% }); %>
</script>
Menu View:
var MenusView = Backbone.View.extend({
initialize:function () {
this.render();
},
tagName: "ul",
events: {
"click li.menucls" : "openMenuItem"
},
openMenuItem: function(e){
currentLink = $(e.currentTarget);
menuId = currentLink.data('menu_id');
tableId = currentLink.parent().data('table_id');
app.navigate("table" + tableId + "/menu" + menuId + "/", true);
console.log("menuId: " + menuId );
console.log("tableId: " + tableId );
},
render:function () {
var that = this;
var menus = new Menus();
menus.fetch({
success: function (menus) {
var template = _.template($('#menu-template').html(), {menus: menus.models});
that.$el.html(template);
}
})
}
});
And there is my goal .... After click I need link like .../table:id/menu:id/
There is my json and collections....
tables.json
[
{"name": "Table 1","stts": "redstts","id": 1},
{"name": "Table 2","stts": "redstts","id": 2},
{"name": "Table 3","stts": "redstts","id": 3},
{"name": "Table 4","stts": "redstts","id": 4},
{"name": "Table 5","stts": "redstts","id": 5}
]
menus.json
[
{"name": "Menu 2","id": 1},
{"name": "Menu 2","id": 2}
]
var Table = Backbone.Model.extend({
defaults: {"name": "Table unahmed"}
});
var Tables = Backbone.Collection.extend({
url: 'api/tables.json',
model: Table
});
var Menu = Backbone.Model.extend({
defaults: {"name": "Menu unahmed"}
});
var Menus = Backbone.Collection.extend({
url: 'api/menus.json',
model: Menu
});
My main js
var AppRouter = Backbone.Router.extend({
routes: {
"" : "tables",
"orders" : "orders",
"tables" : "tables",
"table:id/menus" : "menus",
"products" : "products",
"table:id/menu:id/" : "categories"
},
initialize: function () {
this.headerView = new HeaderView();
$('.header').html(this.headerView.el);
},
tables: function () {
if (!this.TablesView) {
this.TablesView = new TablesView();
}
$('#content').html(this.TablesView.el);
this.headerView.selectMenuItem('tables-menu');
},
menus: function () {
if (!this.MenusView) {
this.MenusView = new MenusView();
}
$('#content').html(this.MenusView.el);
this.headerView.selectMenuItem('menus-menu');
},
categories: function (tableId, menuId) {
if (!this.CategoriesView) {
this.CategoriesView = new CategoriesView();
}
$('#content').html(this.CategoriesView.el);
this.headerView.selectMenuItem('categories-menu');
},
products: function () {
if (!this.ProductsView) {
this.ProductsView = new ProductsView();
}
$('#content').html(this.ProductsView.el);
this.headerView.selectMenuItem('products-menu');
}
});
utils.loadTemplate(['HeaderView'], function() {
app = new AppRouter();
Backbone.history.start();
});
I still try to make function event bud without results... events is function but in link is
#tableundefined/menu1/
I'm very grateful for every answer.
Regards Makromat !!!
You should consider separating out the tables and menus into individual json files because the design you have has the Tables and Menus Backbone collection holding the same data. You should also define a model in each of your collections so the collection knows what object to create.
// tables.json
[
{"id": 1, "name": "Table 1"},
{"id": 2, "name": "Table 2"},
]
// menus.json
[
{"id": 1, "name": "Menu 1"},
{"id": 2, "name": "Menu 2"}
]
var Table = Backbone.Model.extend({
defaults: {"name": "Unnamed Table"}
});
var Tables = Backbone.Collection.extend({
url: 'api/tables.json',
model: Table
});
var Menu = Backbone.Model.extend({
defaults: {"name": "Unnamed Menu"}
});
var Menus = Backbone.Collection.extend({
url: 'api/menus.json'
model: Menu
});
Also, consider taking a look a Backbone's router to handle the change of state as the user clicks on different links.
When you define a route that uses multiple variables, they need to be unique and the function handling the route should define the corresponding parameters.
// sample route
'table:tableId/menu:menuId' : 'categories'
// sample handler
categories: function (tableId, menuId) {
// TODO: use tableId and menuId to set your application's state
// possibly by fetching a specific collection or setting a view's model
}
I am building a comment object using Backbone.js.
The URL in the collection returns json that looks like this:
{'type': 'comment',
'data': [{"body": "commment number 1!",
"create_dt": 1343166264000,
"comment_id": 1, "depth": 0,
"user": {"sid": "1",
"uid": "1",
"name": "Amie C",
"level": "2"},
"sid": 1
},
{"body": "commment number 1-1!",
"create_dt": 1343166361000,
"comment_id": 4,
"depth": 1,
"user": {"sid": "1",
"uid": "1",
"name": "lila M",
"level": "2"},
"sid": 1}
}]
}
The url works in the browser and I was able to see all my json coming back. However, the problem I am having is there is no data coming back when loading the comment.js. I would see a Get request that's red yet said 200 OK and has no body in the response. Also my model's lenth is 0.
Thanks much in advanced.
Here is comment.js:
//default comment model
var Comment = Backbone.Model.extend({
defaults: {
body: "",
create_dt: null,
comment_id: null,
depth: null,
user: null,
sid: null
}
});
//instaitiate a new comment
var comment = new Comment;
//default event view
var CommentView = Backbone.View.extend({
tagName: "li",
className: "comment",
initialize: function(){
this.render();
},
render: function(){
$(this.el).html(this.model.toJSON());
return this;
}
});
//default comments collection
var Comments = Backbone.Collection.extend({
model: Comment,
initialize: function(){
},
url:"http://127.0.0.1/test/objects/json/comments.json",
parse: function(resp) {
return resp.data;
}
});
//default eventsview for events collection's view
var CommentsView = Backbone.View.extend({
tagName: "ul",
className:"comments",
intialize: function(){
this.render();
},
render: function(){
_.each(this.collection.models, function(comment){
//init the CommentView and passed in its model here
var commentView = new CommentView({model: comment});
$(this.el).prepend(commentView.render().el)
}, this);
return this;
}
});
//instantiate new events collection
var comments = new Comments;
var commentsView = new CommentsView({collection: comments});
//on the new events collection, we fetch the data from URL
comments.fetch({
error:function(response, xhr){
console.log(response);
console.log(xhr)
},
success:function(){
console.log("success");
$('.comments_container').html(commentsView.render().el);
}
});
And the html looks like this:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Share</title>
<link rel="stylesheet" href="share.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="js/comment.js"></script>
</head>
<body>
<div class="main_app">
<div class="comments_container"></div>
</div>
</body>
</html>
The problem I think is here in CommentView:
render: function(){
$(this.el).html(this.model.toJSON());
return this;
}
this.model.toJSON() does not return a string, so it won't show when you place it directly into the html like that.
Try this instead:
$(this.el).html(JSON.stringify(this.model));
I am trying to get backbone.js to load json.
The json loads but i am not sure how to get the items into my collection.
Or maybe that happens automatically and i just can't trace out. scope issue?
//js code
//model
var Client = Backbone.Model.extend({
defaults: {
name: 'nike',
img: "http://www.rcolepeterson.com/cole.jpg"
},
});
//collection
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json'
});
//view
var theView = Backbone.View.extend({
initialize: function () {
this.collection = new ClientCollection();
this.collection.bind("reset", this.render, this);
this.collection.bind("change", this.render, this);
this.collection.fetch();
},
render: function () {
alert("test" + this.collection.toJSON());
}
});
var myView = new theView();
//json
{
"items": [
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
}
Your json is not in the correct format, you can fix the json or add a hint to backbone in the parse method:
var ClientCollection = Backbone.Collection.extend({
defaults: {
model: Client
},
model: Client,
url: 'json/client.json',
parse: function(response){
return response.items;
}
});
Or fix your JSON:
[
{
"name": "WTBS",
"img": "no image"
},
{
"name": "XYC",
"img": "no image"
}
]
If you use rest api, try turn off these parameters:
Backbone.emulateHTTP
Backbone.emulateJSON