JSON item to Backbone Model - javascript

I'm using backbone.js. I get a json like this:
{
first_name: 'David',
last_name: 'Smith',
family: [{father: 'David', mother: 'Rose', brother: 'Max'}]
}
first_name and last_name shows in through a PersonView (extending Backbone.View) and family data I want to show in a DetailsView.
So, I was trying like this. First:
personView = new PersonView(model: person)//person it's the json above
PersonView shows well. Then I want to pass the model to DetailsView like this:
detailsView = new DetailsView(model: JSON.parse(person.get('family'));
Well, when I try to pass the model to a template in DetailsView implementation, like this:
DetailsView = Backbone.View.extend({
className: 'tab-pane',
template: _.template($('#detail-tpl').html()),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
I get this message:
Uncaught TypeError: Object [object Object] has no method 'toJSON'
I don't know how to get or pass the model to solved this.
I'm trying several ways but I can't make it go.
Hope you can help me.

I think the problem is is because of this line.
model: JSON.parse(person.get('family')
It expects model to be an instance of backbone Model . But I don't think that is the case here.. try defining the Model for family or otherwise change the name of the key
Instead try this approach
familyMembers : JSON.parse(person.get('family')
In your view you can access this as
(this.options.familyMembers.toJSON())

The issue is that you model you are passing in is just an array. Therefore doesn't have the .toJSON method. As grant suggested you could use new Backbone.Model when creating the view but I would recommend using a collection and 2 new views for the family. It would look something like this.
var PersonModel = Backbone.Model.extend({
initialize: function(attributes, options) {
if(attributes.family) {
this.family = new FamilyCollection(attributes.family, options);
}
}
});
var FamilyCollection = Backbone.Collection.extend({
model: FamilyMember,
initialize: function(models, options) {
this.view = new FamilyView(options);
}
});
var FamilyMember = Backbone.Model.extend({
initialize: function(attributes, options) {
this.view = new DetailedView({
model: this
});
}
});
Then you would use a view structure something like this..
<div class="person">
<span class="name-first">David</span> <span class="name-last">Smith</span>
<div class="family-members>
<div class="family-member">
<span class="name-first">Rose</span> <span class="name-last">Smith</span>
</div>
<div class="family-member">
<span class="name-first">David</span> <span class="name-last">Smith</span>
</div>
<div class="family-member">
<span class="name-first">Max</span> <span class="name-last">Smith</span>
</div>
</div>
</div>

The "family" property is an array, you could do one of the following...
var familyArray = model.get('family');
new DetailsView({model: new Backbone.Model(familyArray[0])});
...or add a getFamily function to the person model...
var PersonModel = Backbone.Model.extend({
getFamily: function() {
var familyArray = this.get('family');
return new Backbone.Model(familyArray[0]);
}
});
...
new DetailsView({model: person.getFamily()});

Related

Rendering a table with Backbone

I need help with my code, I'm trying to learn Backbone for my Social Project. I'm trying to render a view from a collection that I got from an API (deployd API)
Here is the HTML code for the table:
<div class="container-fluid">
<table id= "teachers">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Code</th>
<th>Last time online</th>
</tr>
</thead>
<tbody id="table-body"></tbody>
</table>
</div>
<script type="text/template" id="teacher-template">
<td><%= name %></td>
<td><%= lastname %></td>
<td><%= code %></td>
<td><%= lastactivity %></td>
</script>
Here is the JS code:
var TeacherModel = Backbone.Model.extend({
defaults: {
id:'',
name: '',
lastname: '',
code: '',
lastactivity: ''
}
});
var TeacherCollection = Backbone.Collection.extend({
url: "/teachers",
model: TeacherModel
});
var teachercollection = new TeacherCollection();
teachercollection.url = '/teachers';
teachercollection.fetch({
success: function(collection, response) {
console.log("Done!!");
}, error: function(collection, response) {
alert(response);
}
});
var TeachersView = Backbone.View.extend({
el: '#table-body',
initialize: function() {
this.render();
},
render: function() {
this.$el.html('');
teachercollection.each(function(model) {
var teacher = new TeacherView({
model: model
});
this.$el.append(teacher.render().el);
}.bind(this));
return this;
}
});
var TeacherView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#teacher-template').html()),
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
// Launch app
var app = new TeachersView;
So my question is, how I can pass a collection to a view, or a model of the collection to a view? I want to render the data in each row from the table. The browser gets the collection, as you can see here:
I've been trying for days, and I just can't understand the logic, I have read the documentation, and a little of the Addy Osmani's book but just can't get my head on it, can someone explain it to me? Been looking for answers in this site but some on them include some "add models" stuff, which confuse me more.
(The parameters of the model in the image, differ from the code. I'd translate to make it more easy to understand.)
how I can pass a collection to a view, or a model of the collection to a view?
You are already doing that in your code:
var teacher = new TeacherView({
model: model
});
Here you're passing a model to view's constructor using model option.
You can pass a collection to view via it's constructor like:
var app = new TeachersView({
collection:teachercollection
});
Which you can access inside the view via this.collection and this.model respectively.
var TeachersView = Backbone.View.extend({
el: '#table-body',
initialize: function() {
this.render();
},
render: function() {
this.$el.html('');
this.collection.each(function(model) {
this.$el.append(new TeacherView({
model: model
}).el);
},this);
return this;
}
});
Note that fetch() is asynchronous, so you'll need to wait till it succeeds before rendering the view.
See the suggestions in this answer regarding the changes I made to your render method.
this answer might help understanding a thing or two.

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

Knockout.js not updating bindings in select field

I have an issue with Knockout.js . What I try to do is filter a select field. I have the following html:
<select data-bind="options: GenreModel, optionsText: 'name', value: $root.selectedGenre"></select>
<ul data-bind="foreach: Model">
<span data-bind="text: $root.selectedGenre.id"></span>
<li data-bind="text: name, visible: genre == $root.selectedGenre.id"></li>
</ul>
And the js:
var ViewModel = function (){
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
JSFiddle: http://jsfiddle.net/CeJA7/1/
So my problem is now that the select list does not update the binding on the span inside the ul and I don't know why...
The value binding should update the property selectedGenre whenever the select value changes, shouldn't it?
Any ideas are welcome.
There are a lot of issues in your code:
1) self is not a magical variable like this. It's something people use to cope with variable scoping. Whenever you see self somewhere in a JavaScript function be sure there's a var self = this; somewhere before.
2) KnockoutJS observables are not plain variables. They are functions (selectedGenre = ko.observable()). ko.observable() returns a function. If you read the very first lines of documentation regarding observables you should understand that access to the actual value is encapsulated in this retured function. This is by design and due to limitations in what JavaScript can and cannot do as a language.
3) By definition, in HTML, <ul> elements can only contain <li> elements, not <span> or anything else.
Applying the above fixes leads to this working updated sample:
HTML:
<select data-bind="options: GenreModel, optionsText: 'name', value: selectedGenre"></select>
<span data-bind="text: $root.selectedGenre().id"></span>
<ul data-bind="foreach: Model">
<li data-bind="text: name, visible: genre == $root.selectedGenre().name"></li>
</ul>
JavaScript:
var ViewModel = function (){
var self = this;
self.selectedGenre = ko.observable();
self.Model = ko.observableArray([
{
name: "Test",
genre: "Pop"
}
]);
self.GenreModel = ko.observableArray([
{
name: "Pop",
id: "Pop"
},
{
name: "Alle",
id: "All"
}
]);
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);

Knockout mapping plugging does not work properly

Hi I have been getting investing alot of time in learning Knockout and have come to a point where I have to many properties in my application and I am in need to use the mapping pluggin.
It seems easy enought how it should be used but I mussed be missing something because it does not work.I have created a test example.This is my code:
function vm() {
var self = this;
this.viewModel = {};
this.getData = function() {
$.getJSON('/api/Values/Get').then(data)
.fail(error);
function data(ajaxData) {
console.log(ajaxData);
self.viewModel = ko.mapping.fromJS(ajaxData);
console.log(self.viewModel);
}
function error(jError) {
console.log(jError);
}
};
};
ko.applyBindings(new vm());
This is my html:
<ul data-bind="foreach: viewModel">
<li data-bind="text:FirstName"></li>
<input type="text" data-bind="value: FirstName"/>
</ul>
<button data-bind="click : getData">Press me!</button>
My ajax call succesfully retrieves this data from the server:
[
{
FirstName: "Madalina",
LastName: "Ciobotaru",
hobies: [
"games",
"programming",
"hoby"
]
},
{
FirstName: "Alexandru",
LastName: "Nistor",
hobies: [
"games",
"programming",
"movies"
]
}
]
It seems that after data function is called viewModel get's converted into an array but with no items in it.
What am I doing wrong?
I have taken your expected server data and created a jsfiddle here. You needed to change the viewModel property to be an observable array, and change the way the mapping is performed.
Here is a version of your script that will work:
function vm() {
var self = this;
this.viewModel = ko.observableArray([]);
this.getData = function() {
$.getJSON('/api/Values/Get').then(data)
.fail(error);
function data(ajaxData) {
console.log(ajaxData);
ko.mapping.fromJS(ajaxData, {}, self.viewModel);
console.log(self.viewModel);
}
function error(jError) {
console.log(jError);
}
};
};
ko.applyBindings(new vm());

Backbone.js adding sub-view elements to parent-view's element

I have a collection view and a model view, like so:
EventListView
|-- EventView
EventListView must display many EventViews in a one-to-many relationship. I am using the underscore _.template() function to build my views templates.
Here is my EventView template:
<h1>
<span class="date"><%= prefix %><%= dateString %></span>
<span class="title"><%= title %></span>
</h1>
<div class="caption"><%= caption %></div>
My EventView render method:
render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
And here is my EventListView template:
<h1>
<% if(typeof(title) != "undefined") { print(title) } %>
</h1>
<%= events %>
And it's render method:
// this._EventViews is an array of eventView objects
render: function() {
var templateData = {
events: _.reduce(this._EventViews, function(memo, eventView) { return memo + eventView.$el.html(); }, "")
}
this.$el.html(this.template(templateData));
return this;
}
The problem I am having is that eventView.$el.html() contains only the HTML in my template, but I need to take advantage of the tagName, className and id attributes that Backbone views support.
Consider if I set up EventView like so:
return Backbone.View.extend({
model: EventModel
, tagName: 'article'
, className: 'event'
, template: _.template(templateText)
, render: function () {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
I want to insert:
<article class="event" id="someID342">
<h1>
<span class="date">01/02/2010</span>
<span class="title"></span>
<div class="caption></div>
</h1>
</article>
but eventView.$el returns:
<h1>
<span class="date">01/02/2010</span>
<span class="title"></span>
<div class="caption></div>
</h1>
How do I insert the entire eventView element? Not just it's innerHTML.
Just reserve placeholder in your EvenListView's template
<h1><%- title %></h1>
<div class="js-events"></div>
And then render and append child views
render: function() {
this.$el.html(this.template({title: 'Title'}));
this.$events = this.$('.js-events');
_.each(this._EventViews, function (eventView) {
this.$events.append(eventView.render().$el);
}, this);
return this;
}
The render() function shouldn't be responsible for handling the setup of the view.el. This is done by Backbone in the _ensureElement function that is called when you initialize the view.
Also, the $.fn.html() function is only supposed to return the contents of the selected element.
You have many options but I think the most flexible and sustainable approach is to get each sub view to define its own template. The parent view simply appends the child elements .el property.
The advantages of this approach, your template is only compiled once. And updates to children do not require re-rendering parent and neighbouring elements.
Here is a JSBin
Example:
var ContainerView = Backbone.View.extend({
tagName: "article",
className: "event",
id: "someID342",
initialize: function(options){
//the template will now be rendered
this.childView = new ChildView()
//the rendered child will now appear within the parent view
this.el.appendChild( this.childView.el )
}
})
var ChildView = Backbone.View.extend({
tagName: "h1",
dateString:"01/02/2010",
prefix: "Date: ",
caption: "What a wonderful date!:",
title: "I am a title",
template: _.template([
'<h1>',
'<span class="date"><%= prefix %><%= dateString %></span>',
'<span class="title"><%= title %></span>',
'</h1>',
'<div class="caption"><%= caption %></div>'
].join("")),
initialize: function(){
this.render()
},
render: function(){
// because you are only altering innerHTML
// you do not need to reappend the child in the parent view
this.el.innerHTML = this.template(this)
}
})
I'd personally caution against using templates in Backbone at all. I've found that simply having a Backbone view for every component of your app becomes a lot easier to edit later. Sharing templates is a lot harder than sharing views. Of course it depends on the requirements of your project.

Categories

Resources