Handeling response from backbone.js collection using fetch - backbone.js

am pretty new to backbone.js and managed recently to finish my first application. I made a collection that is responsible for fetching data through a API but am not able to loop through the result and use it.
Here is my model file
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone){
var VehicleLookupModel = Backbone.Model.extend({
//data will contain one of the items returned from the collection's 'parse' function.
parse: function(data){
return data;
}
})
return VehicleLookupModel;
});
collection file
define([
'jquery',
'underscore',
'backbone',
'l/models/VehicleLookupModel'
], function($, _, Backbone, VehicleLookupModel){
var VehicleLookupModelSet = Backbone.Collection.extend({
model : VehicleLookupModel,
url : function() {
return '/en/car/api/model-lookup-model.json/'+this.make+'/';
},
parse : function(response) {
return response;
},
initialize: function(options) {
options || (options = {});
this.make = options.make;
}
})
return VehicleLookupModelSet;
});
and finally the view file
define([
'jquery',
'underscore',
'backbone',
'l/collections/VehicleLookupMakeSet',
'l/collections/VehicleLookupModelSet',
'l/collections/VehicleLookupTrimSet'
], function($, _, Backbone, VehicleLookupMakeSet, VehicleLookupModelSet, VehicleLookupTrimSet){
var BrowseVehicleView = Backbone.View.extend({
el: $('#vehicle-browse-form'),
initialize: function(){
// Extend JQuery example
// This would extend JQuery function for resetting elements on the form
$.fn.extend({
resetElement: function(){
$(this).attr('disabled', 'disabled');
$(this).html('');
return $(this);
}
});
// define array of elements to be used in DOM manipulations
this.elements = {
"make" : $('#id_make', this.el),
"model" : $('#id_model', this.el),
"trim" : $('#id_trim', this.el),
"year" : $('#id_year', this.el)
}
},
events: {
"change #id_make" : "onMakeChange",
"change #id_model" : "onModelChange",
"change #id_trim" : "onTrimChange"
},
render: function(){
// Using Underscore we can compile our template with data
},
onMakeChange: function(event) {
this.elements.model.resetElement();
this.elements.trim.resetElement();
this.collection = new VehicleLookupModelSet({make: this.elements.make.val()})
this.collection.fetch();
console.log(this.collection);
},
onModelChange: function(event) {
var VehicleLookupTrimInstance = new VehicleLookupTrimSet({make: this.elements.make.val(), model: this.elements.model.val()})
VehicleLookupTrimInstance.fetch();
},
onTrimChange: function(event) {
},
renderItem: function(object, item) {
console.log(item);
}
});
// Our module now returns our view
return new BrowseVehicleView;
});
The above is console.log(this.collection) is returning an object with many property which am not sure how to use. But, I noticed that there is a method "models" and inside models there is many number of objects, each represent the value of the json.
Any ideas how i can loop through the object?

this.collection.fetch({
success: function(collection, response) {
_.each(collection.models, function(model) {
console.log(model.toJSON());
})
}
});

Related

Backbone view 1 pass value to another view 2

This is the first view content ,where the second view is loaded to first view as a child.
define([ 'jquery', 'underscore', 'backbone',
'text!../../../../school-admin/classManagement.html',
'views/schoolModule/stdManagementView'],
function($, _, Backbone, hrManagementTemplate,StdManagementView) {
var ClassManagementView = Backbone.View
.extend({
// target item.
el : $("#schoolContentOuterPnl"),
render : function() {
var data = {};
// template
var compiledTemplate = _.template(hrManagementTemplate, data);
// append the item to the view's target
this.$el.html(compiledTemplate);
},
// Event Handlers
events : {
"click #btnStdInClassManagement" : "loadStdInClassManagement",
},
loadStdInClassManagement : function(){
//Here i want to pass value to another view
new StdManagementView({
el : $("#classManagementContenTtabContent")
});
},
});
return new ClassManagementView;
});
This is my second view ,when the event on the first view is triggered.
define([ 'jquery', 'underscore', 'backbone', 'datatables',
'text!../../../../school-admin/stdManagement.html' ],
function($, _, Backbone, datatables, stdManagementTemplate) {
var StdManagementView = Backbone.View.extend({
initialize: function(){
this.render();
},
render : function() {
var data = {};
// template
var compiledTemplate = _.template(
stdManagementTemplate, data);
// append the item to the view's target
this.$el.html(compiledTemplate);
},
// Event Handlers
events : {},
});
return StdManagementView;
});
From the above code how can i pass a dynamic value from view 1 to view 2.
From your code it looks like you only want to pass in a value once when you create your second view. As such you can just pass it in to the constructor of your second view and it will be part of the options object passed in.
For example
//view 1
loadStdInClassManagement : function(){
//Here i want to pass value to another view
new StdManagementView({
el : $("#classManagementContenTtabContent"),
someValue: 'something'
});
}
//view 2
var StdManagementView = Backbone.View.extend({
initialize: function(options){
this.someValue = options.someValue;
this.render();
},

get model by id from collection in backbonejs

I have following kind of collection
[
{
"id": "2324324",
"name": "name",
"type": "type",
},
{
"id": "59980",
"name": "name",
"type": "type",
}
]
model:
define(['underscore', 'backbone'], function(_, Backbone){
//Define Alert model with default properties and value
var abcModel = Backbone.Model.extend({
idAttribute:"_id",
defaults:{
// My properties
},
initialize:function(){
}
});
return abcModel;
});
collection
define(['underscore', 'backbone', 'models/abcModel', 'app/utils'], function(_, Backbone, abcModel, Utils) {
var self;
//List of Alerts stored in Backbone Collection
abcListCollection = Backbone.Collection.extend({
model: abcModel ,
initialize: function() {
self = this;
this.model=abcModel ;
},
fetchData: function(obj) {
add=true;
var data = {
"method": "method name",
"params": {
param1:"param1",
param2:"param2"
}
}
Utils.Ajax.post(Utils.WebAPI.WebAPIServer, data, function(response, textStatus, jqXHR) {
obj.success.call(self.collection, response);
}, 'json', function(err) {
console.log(JSON.stringify(err));
obj.error.call(err);
}, "loading");
},
collection: {}
});
return abcListCollection;
});
view
define(['jquery', 'underscore', 'backbone', 'text!views/abcView/abcListView.html','views/abcView/ListTemplate' ,'app/utils', 'collection/abcListCollection'], function($, _, Backbone, tmpl_abcummaryView, abcListView, Utils, abcListCollection) {
var abcListView = Backbone.View.extend({
// Setting the view's template property using the Underscore template method
template: _.template(tmpl_abcummaryView),
// View constructor
initialize: function() {
abcCollection= new abcListCollection();
mainRouter.collections.abc= new abcListCollection();
},
// View Event Handlers
events: {
},
// Renders the view's template to the UI
render: function() {
var self=this;
this.$el.html(this.template({data: this.templateData}));
abcCollection.fetchData({
success: function (collection, response) {
_.each(collection, function (obj) {
mainRouter.collections.abc.add(obj);
})
},
error: function (err) {
console.log("error");
}
});
var model1=mainRouter.collections.abc.get(2324324);
// Maintains chainability
return this;
}
});
return abcListView;
});
var model1=mainRouter.collections.abc.get(2324324);
But it is returning undefined.
You could try
mainRouter.collections.abc.findWhere( { id : 2324324 });
However, it seems that your timing could also be out.
the .fetchData function would be an asynchronous call, meaning that the success function would actually execute after the line
var model1 = mainRouter.collectins.abc.get(2324324);
Put a debug breakpoint on the above line, and also the success function - and see which one executes first.
Your fetchData is a asynchronous function. It would be executed in the event loop after that async call is resolved. Your code is not blocking at that call. It just goes over that and executes the render function completely. After some time, when that call would return and your success callback would be called, you get something in your collection.
Putting the code of getting the model from the collection is right and should be put in a callback after you have added models to the collection.
see Collection get http://backbonejs.org/#Collection-get
so one way to do is to write:
success: function (collection, response) {
_.each(collection, function (obj) {
mainRouter.collections.abc.add(obj);
})
var model1 = mainRouter.collectins.abc.get(2324324);
},
However it does not seem right to use your model in your view. but that is the design issue that you have to think about.
Also, i think that you should read a little more about Javascript event driven architecture. I have written a simple blog : Learning Javascript

Backbone collection trigger twice when going back

I have a weard issue with a collection, when I first load my compositeView everything is working great but then when I start navigate in my app and then comeback to my compositeView(Backbone.history.navigate) it looks like my collection is called twice (my itemviews are fired twice).
I have try to debug, but I fetch my collection only once, the is only one init, the router seems to be ok too.
Here is my compositeView:
'use strict';
define(["jquery", "backbone", "marionette", "text!templates/portraits/portrait.html", "view/portraits/portraitItemView", "collection/portraitCollection", "application", "JSMovieclip"], function($, Backbone, Marionette, template, PortraitItemView, portraitCollection, App) {
var PortraitsCompositeView = Marionette.CompositeView.extend({
template : _.template(template),
collection : portraitCollection,
tagName: "div",
id : "articles",
itemView : PortraitItemView,
itemViewContainer : '#list-articles',
itemViewOptions: {
collection: portraitCollection
},
initialize : function (options) {
_.bindAll(this);
this.options = options || {};
this.collection.fetch({
type: 'POST',
success : function(data, raw) {
App.execute('loader', false);
}
});
},
And here is my collection :
'use strict';
define(["jquery", "underscore", "backbone", "marionette", "model/portraitsModel"], function($, _, Backbone, Marionette, PortraitModel) {
var PortraitCollection = Backbone.Collection.extend({
model : PortraitModel,
sync: function(method, model, options) {
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: 'http://backend.url.fr/api/portraits/get_list/',
processData: false
}, options);
return $.ajax(params);
},
parse : function(response) {
this.totalLength = response.count;
return response.portraits;
}
});
return new PortraitCollection;
});
Your collection fetch is appending the items to itself.
You can add reset:true to your Collection.fetch properties
initialize : function (options) {
_.bindAll(this);
this.options = options || {};
this.collection.fetch({
reset: true,
type: 'POST',
success : function(data, raw) {
App.execute('loader', false);
}
});
},
I finally found my error, my json was returning an empty "id" field, after fixing it, everything works great.

Backbone collection length always set to one with nested views

When the view is loaded, the collection length always return 1 while there is currently 3 members shows up in the parse function. I wondered if the problem was the nested item view, but it seems to behave the same without ! I don't understand why the self.push(member) does not add the model to the collection ! Bit stuck here, any help please ?
The model
define([
'backbone'
], function(Backbone) {
'use strict';
var MemberModel = Backbone.Model.extend({
id: "_id"
});
return MemberModel;
});
The collection
define([
'backbone',
'models/MemberModel'
], function(Backbone, MemberModel) {
'use strict';
var Members = Backbone.Collection.extend({
model: MemberModel,
url: '/api/v1/users',
parse: function(response, options) {
var self = this;
_.each(response.users, function(item){
var member = new self.model();
member.set('email', item.email);
member.set('firstname', item.firstname);
member.set('lastname', item.lastname);
member.set('group', item.group);
member.set('city', item.city);
// shows every member's emails
console.log('member.email='+member.get('email'));
self.push(member);
});
console.log('this.length='+this.length); // this is always equal to 1
return this.models;
}
});
return Members;
});
The view
define([
'collections/members',
'views/membersItem',
'text!templates/members.html'
], function(MembersCollection, MembersItem, membersTpl) {
'use strict';
var Members = Backbone.View.extend({
el: '#settings-content',
template: _.template(membersTpl),
events: {
'click #edit-member': 'editMember'
},
initialize: function() {
this.collection = new MembersCollection();
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
var self = this;
this.collection.fetch({
success: function() {
self.renderMember();
}
});
return this;
},
renderMember: function() {
// same here collection length = 1
console.log('collection.length:'+this.collection.length);
_.each(this.collection.models, function (item) {
var memberView = new MembersItem({model: item});
$('.list-item', this.el).append(memberView.render().el);
}, this);
}
});
return Members;
});
The nested item view
define([
'text!templates/members_item.html'
], function(membersItemTpl) {
'use strict';
var MembersItem = Backbone.View.extend({
tagName: "tr",
className: '.item',
template: _.template(membersItemTpl),
initialize: function() {
this.model.bind("change", this.render, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
return MembersItem;
});
Looks like the problem is with duplicated id's in the collection. It is supposed to be a unique Identifier.
Set the idAttribute inside the model and make sure, the id's for the 3 objects in question are different.
var MemberModel = Backbone.Model.extend({
idAttribute: "_id"
});
If your id is duplicated then the model will not be added to the model.
If that does not work try setting the id Attribute explicitly
_.each(response.users, function(item, index){
var member = new self.model();
member.set('_id', index);

uncaught typeerror: object function has no method 'tojson'

I have created a model like this
define(['backbone', 'text_dictionary'], function(Backbone, Text_Dict) {
var IndexPageModel = Backbone.Model.extend({
defaults:{
val_btn_gotohomepage : Text_Dict.val_btn_gotohomepage,
val_btn_gotologinpage : Text_Dict.val_btn_gotologinpage,
val_btn_gotolistpage : Text_Dict.val_btn_gotolistpage
}
});
return IndexPageModel;
});
and instantiated this model with 'new' in my page code like this
define([ 'page_layout',
'panel_itemview',
'header_itemview',
'content_itemview',
'footer_itemview',
'templates',
'text_dictionary',
'indexpage_model',
'indexpage_logic'],
function( Page,
Panel,
Header,
Content,
Footer,
Templates,
Text_Dict,
IndexPageModel,
IndexPage_BusnLogic) {
console.log("Success..Inside Index Page.");
var Page_Index = {};
Page_Index.page = (function(){
var _pageName = Text_Dict.indexpage_name;
var _pageModel = new IndexPageModel();
return _pageLayout = Page.pageLayout({
name:_pageName,
panelView: Panel.panelView({name:_pageName, pagetemplate: Templates.simple_panel}),
headerView: Header.headerView({name:_pageName, title: Text_Dict.indexpage_header, pagetemplate: Templates.header_with_buttons}),
contentView: Content.contentView({name:_pageName, page_model:_pageModel, pagetemplate:Templates.content_index, busn_logic:IndexPage_BusnLogic.HandleEvents}),
footerView: Footer.footerView({name:_pageName, title: Text_Dict.indexpage_footer, pagetemplate: Templates.simple_footer})
});
})();
return Page_Index;
});
my page gets created using the page layout
define([ 'underscore', 'marionette' ], function( _, Marionette ) {
console.log("Success..Inside Index View.");
var Page = {};
var _ReplaceWithRegion = Marionette.Region.extend({
open: function(view){
//Need this to keep Panel/Header/Content/Footer at the same level for panel to work properly
this.$el.replaceWith(view.el);
}
});
Page.pageLayout = function (opts) {
var _opts = _.extend ({ name: 'noname',
panelView: null,
headerView: null,
contentView: null,
footerView: null,
}, opts);
return new ( Marionette.Layout.extend({
tagName: 'section',
attributes: function() {
return {
'id': 'page_' + _opts.name,
'data-url': 'page_' + _opts.name,
'data-role': 'page',
'data-theme': 'a'
};
},
template: function () {
return "<div region_id='panel'/><div region_id='header'/><div region_id='content'/><div region_id='footer'/>";
},
regions: {
panel: {selector: "[region_id=panel]", regionType: _ReplaceWithRegion},
header: {selector: "[region_id=header]", regionType: _ReplaceWithRegion},
content: {selector: "[region_id=content]", regionType: _ReplaceWithRegion},
footer: {selector: "[region_id=footer]", regionType: _ReplaceWithRegion},
},
initialize: function(){
$('body').append(this.$el);
this.render();
},
onRender: function() {
if (this.options.panelView) {
this.panel.show (this.options.panelView);
};
if (this.options.headerView) {
this.header.show (this.options.headerView);
};
if (this.options.contentView) {
this.content.show(this.options.contentView);
};
if (this.options.footerView) {
this.footer.show (this.options.footerView);
};
},
}))(_opts);
};
return Page;
});
but in my itemview when i am passing model reference like this
define([ 'underscore', 'marionette', 'event_dictionary', 'app' ], function(_,
Marionette, Event_Dict, App) {
console.log("Success..Inside Content Index View.");
var Content = {};
Content.contentView = function(opts) {
return new (Marionette.ItemView.extend({
tagName : 'div',
attributes : function() {
console.log('options name==' + opts.name);
console.log("page model=="+opts.page_model);
return {
'region_id' : 'content',
'id' : 'content_' + opts.name,
'data-role' : 'content'
};
},
initialize : function() {
_.bindAll(this, "template");
},
template : function() {
return opts.pagetemplate;
},
model : function() {
return opts.page_model;
}
}))(opts);
};
return Content;
});
It's giving me error
Uncaught TypeError: Object function () {
return opts.page_model;
} has no method 'toJSON'
The model property of a view cannot be a function. Backbone allows this for some things like url (by way of the _.result helper function), but not in this case. Change your view code to not have a model function and just do this in initialize:
initialize: function (options) {
this.model = this.page_model = options.page_model;
}
UPDATE since you won't just take my word for it, here is the Marionette source that is almost certainly the top of your exception stack trace. Once again: view.model has to be a model object not a function. Fix that and the error will go away.
The accepted answer is correct, but it took a bit of messing about to find out why I had that error coming up, so I'm offering what the solution for my personal use-case was in case it helps anyone else stumbling upon this page in the future.
I had this:
app.module 'Widget.Meta', (Meta, app, Backbone, Marionette, $, _) ->
Meta.metaView = Backbone.Marionette.ItemView.extend
model: app.Entities.Models.meta
template: '#meta-template'
... when I should have had this:
app.module 'Widget.Meta', (Meta, app, Backbone, Marionette, $, _) ->
Meta.metaView = Backbone.Marionette.ItemView.extend
model: new app.Entities.Models.meta()
template: '#meta-template'
It's just a matter of instantiating the function definition.

Resources