Backobone how can i fetch data and console it - backbone.js

I am very new to use backone.js, i am trying to fetch json data from model and consoling it, but nothing i am getting...
anyone advice me the correct way to console and see the data using while i parse my response in model..
code :
(function($){
var list = {};
list.model = Backbone.Model.extend({
defaults:{
name:'need the name'
},
urlRoot : 'data/names.json',
parse:function(response){
console.log(response);// i am not get any data..
return response.results;
}
});
list.view = Backbone.View.extend({
});
var newList = new list.model;
var newView = new list.view({model:newList});
})(jQuery)

You should call fetch method.
You can do this inside model initialize method:
initialize : function() {
this.fetch();
}
Or after creating model instance:
var newList = new list.model;
newList.fetch();
EDIT:
Fiddle:
var list = {};
list.model = Backbone.Model.extend({
defaults : {
name : 'need the name'
},
url : 'https://graph.facebook.com/4?fields=id,name',
initialize : function(response) {
this.fetch();
},
parse : function(response){
console.log(response); // <- {"id":"4","name":"Mark Zuckerberg"}
return response;
}
});
list.view = Backbone.View.extend({});
var newList = new list.model;
var newView = new list.view({model:newList});

Related

Adding model to a collection after save method in backbone

I am using the save method when my data is submitted. On success callback of the save method, the collection should be updated with the model which i have saved since i want to get the id of the model from my server. My code is as below
var app = app || {};
app.AllDoneView = Backbone.View.extend({
el: '#frmAddDone',
events:{
'click #addDone':'addDone'
},
addDone: function(e ) {
e.preventDefault();
var formData = {
doneHeading: this.$("#doneHeading").val(),
doneDescription: this.$("#doneDescription").val(),
};
var donemodel = new app.Done();
donemodel.save(formData,
{
success :function(data){
/*my problem is here how do i listen to collection event add that has been
instantiated in intialize property to call renderDone . My tried code is
var donecollection = new app.AllDone();
donecollection.add(donemodel);
and my response from server is
[{id:145, doneHeading:heading , doneDescription:description,
submission_date:2014-08-27 03:20:12}]
*/
},
error: function(data){
console.log('error');
},
});
},
initialize: function() {
this.collection = new app.AllDone();
this.collection.fetch({
error: function () {
console.log("error!!");
},
success: function (collection) {
console.log("no error");
}
});
this.listenTo( this.collection, 'add', this.renderDone );
},
renderDone: function( item ) {
var doneView = new app.DoneView({
model: item
});
this.$el.append( doneView.render().el );
}
});
Collection is
var app = app || {};
app.AllDone = Backbone.Collection.extend({
url: './api',
model: app.Done,
});
Model is
var app = app || {};
app.Done = Backbone.Model.extend({
url: "./insert_done",
});
View is
var app = app || {};
app.DoneView = Backbone.View.extend({
template: _.template( $( '#doneTemplate' ).html() ),
render: function() {
function
this.$el.html( this.template( this.model.attributes ) );
return this;
}
});
In your success callback you create an entirely new collection, which doesn't have any listeners registered. This is the reason why the renderDone isn't triggered.
The model you receive from the server should be added to the collection which is attached directly to your view, this.collection:
var self = this,
donemodel = new app.Done();
donemodel.save(formData, {
success :function(data){
// this is the collection you created in initialize
self.collection.add(donemodel);
},
error: function(data){
console.log('error');
}
});

How to fetch and filter the data

In my backbone function, all works fine, even the filter. but the issue is, whenever i click on the filter type and switch to another filter type, it is filtering from the existing filtered data, instead of fetching new from server and filter...
in case if i add fetch call over my filter function, it fetch applying all data, without filtering... how can i fix this..?
my code :
$(document).ready(function(){
var school = {};
school.model = Backbone.Model.extend({
defaults:{
name:'no name',
age:'no age'
}
});
school.collect = Backbone.Collection.extend({
model:school.model,
url:'js/school.json',
initialize:function(){
this.sortVar = "name"
}
});
school.view = Backbone.View.extend({
tagName:'div',
className:'member',
template:$('#newTemp').html(),
render:function(){
var temp = _.template(this.template);
this.$el.html(temp(this.model.toJSON()));
return this;
}
});
school.views = Backbone.View.extend({
el:$('#content'),
events:{
'click #newData' : 'newArrival',
'click #showName' : 'showByName',
'click #showAge' : 'showByAge'
},
initialize:function(){
_.bindAll(this);
this.collection = new school.collect;
this.collection.bind('reset', this.render);
this.collection.fetch();
this.childViews = [];
},
newArrival:function(){
this.collection.fetch(); //it works fine, i use this for update
},
showByName:function(){
// this.collection.fetch(); //but i can't do this, it removes filtered data..
this.sortVar = 'name';
var filterType = _.filter(this.collection.models, function(item){
return item.get('name') != '';
})
this.collection.reset(filterType); //resets without fetching (filtering from existing datas..)
},
showByAge:function(){
// this.collection.fetch(); //but i can't do this, it removes filtered data..
this.sortVar = 'age';
var filterType = _.filter(this.collection.models,function(item){
return item.get('age') != 0;
})
this.collection.reset(filterType); //resets without fetching (filtering from existing datas..)
},
render:function(){
_.each(this.childViews, function(old){
old.remove();
});
this.childViews = [];
var that = this;
_.each(this.collection.models, function(item){
that.renderItem(item);
});
},
renderItem:function(item){
var newItem = new school.view({model:item});
this.$el.append(newItem.render().el);
this.childViews.push(newItem);
}
});
var newSchool = new school.views;
});
thanks in advance, as well i do have another 2 methods to add which is sorting the name and age while show the datas.
This is works for me.. thanks all.
showByAge:function(){
var that = this;
this.sortVar = 'age';
this.collection.fetch()
.done(function(){ // i am proceeding after i finish the fetch!
var filterType = _.filter(that.collection.models,function(item){
return item.get(that.sortVar) != 0;
})
that.collection.reset(filterType);
})
},

Save the model from view?

I am developing a Backbone web application and I want to know that how can post data from the view
This is my Model:
App.Models.edit = Backbone.Model.extend({
defaults : {
id : undefined,
fname : undefined,
lname : undefined,
phone : undefined,
address : undefined,
email : undefined,
url: undefined,
},
initialize: function(){
this.set({url : '../api/getOne/' + App.CurrentID });
},
getAttrs: function(attr){
return this.get(attr);
}
});
And this is my view:
App.Views.edit = Backbone.View.extend({
el: $("#modal"),
initialize: function(){
App.TplNames.edit = $('body');
App.Tpls.edit('edit');
this.model.bind("reset", this.render, this);
this.render();
},
events: {
'click .btnSave': 'saveDetails',
},
saveDetails: function(){
this.model.save();
//console.log(this.model);
},
render: function(){
var elem = '';
$.each(this.model.models, function(i, k){
var template = _.template( $('#tpl_edit').html(), k.toJSON() );
elem += template;
});
$(this.el).html(elem);
$("#myModal").modal('show');
$("#myModal").on('hidden', function(){
//alert(123);
document.location.href = App.Url + '#view';
});
var attrs = "";
$.each(this.model.models, function(i, k){
attrs = k.toJSON();
});
$("#fname").val(attrs.fname);
$("#lname").val(attrs.lname);
$("#Email").val(attrs.email);
$("#Phone").val(attrs.phone);
$("#Address").val(attrs.address);
//console.log(attrs);
}
});
And it is my Router
App.Router = Backbone.Router.extend({
routes: {
"" : "def",
"home" : "def",
"view" : "getAll",
"edit/:id" : "edit",
"add" : "addContact",
},
def: function(){
this.mainModel = new App.Collections.Main();
this.mainView = new App.Views.Main({model: this.mainModel});
//this.mainModel.fetch();
},
edit: function(id){
App.CurrentID = id;
var contactCollObj = new App.Collections.edit();
viewObj = new App.Views.edit({model: contactCollObj});
contactCollObj.fetch();
viewObj.render();
//console.log(contactCollObj);
},
getAll: function(){
//alert(123);
var collObj = new App.Collections.View();
var viewObj = new App.Views.View({model: collObj});
collObj.fetch();
},
addContact: function(){
//var model = new App.Collections.AddContact();
model = new App.Models.AddContact();
var view = new App.Views.AddContact({model: model});
//view.render();
}
});
var app = new App.Router();
Backbone.history.start();
And when I want to save the model, It generates an error:
this.model.save is not a function
Every thing is okay except the above...
In your router you pass collection to App.Collections.edit view as model:
var contactCollObj = new App.Collections.edit();
viewObj = new App.Views.edit({model: contactCollObj});
That is why you cannot call save(). save() is only available for a model not a collection.
You probably want to initialize view with collection
viewObj = new App.Views.edit({collection: contactCollObj});
And then also modify some of your view code accordingly.

How to insert results of fetch of model in a view

I've fetch() a model by a server and I want to render the results of fetch() with a view.
The results of fetch() is an array of objects (var risultati) and I want render this var risultati. I've tried but nothing works.
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
},
initialize: function () {},
list: function () {
var utente = new Person();
var risultati;
utente.fetch({
success: function (data) {
var ris = data.attributes;
var risultati = ris.results;
console.log(risultati); /* risultati contains array of object to render*/
}
});
this.page = new UserListView({
model: this.utente
});
$('body').append(this.page.$el);
}
});
You may be having problems because your call to render the view is occurring separate from your utente.fetch() call.
Since .fetch() is asynchronous, your view code will be executed before .fetch() has finished. You should add the view creation/rendering as part of the success function, or you should bind the change event that occurs when the model is updated to fire off a new function that contains your view creation.
You should separate your MVC logic... don't attach objects (collections I think) to a router route handler.
Assuming that you are trying to render a collection of person models, I suggest you use a model and view for the person and a collection and a view for handling the "array of objects" :
var Person = Backbone.Model.extend({
initialize : function(){
// initialize the view
this.view = new PersonView({model : this});
}
}),
PersonView = Backbonke.View.extend({
render : function(){
// render your person
}
}),
UserList = Backbone.Collection.extend({
model : Person,
initialize : function(){
this.view = new UserListView({
collection : this
});
},
update : function(){
var self = this;
this.fetch({
success: function (data) {
var ris = data.attributes;
var risultati = ris.results;
console.log(risultati); /* risultati contains array of object to render*/ self.view.render();
}
});
}
}),
UserListView = Backbone.View.extend({
render : function(){
this.collection.each(function(el,i){
el.view.render();
});
}
});
and then use it as :
var page = new UserList();
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
},
initialize: function () {},
list: function () {
page.update();
}
});
Hope this helps!

Backbone.js add event problem

I have the following backbone.js code and i have a problem in that event before i fetch the "add" event is triggered from the collections. Adding this.field.add(list_fields); in the success: fetch has resulted in an error. How do i make sure the model is fetched then the add event is run after that
$(function() {
$(".chzn-select").chosen();
/*********************************Models*************************************************/
var Table = Backbone.Model.extend({
urlRoot : '/campusfeed/index.php/welcome/generate'
});
var Field = Backbone.Model.extend({
urlRoot: '/campusfeed/index.php/welcome/generate'
});
/**************************Collections*************************************************/
Tables = Backbone.Collection.extend({
//This is our Friends collection and holds our Friend models
initialize : function(models, options) {
this.bind("add", options.view.addFriendLi);
//Listen for new additions to the collection and call a view function if so
}
});
var Fields = Backbone.Collection.extend({
model:Field,
url:'http://localhost/campusfeed/index.php/welcome/generateFields',
initialize : function(models, options) {
this.bind("add", options.view.getFields);
}
});
/************************************Views**************************************************/
var m="shit";
var app = Backbone.View.extend({
el:'body',
initialize:function(model,options){
//Create collections in here
this.table = new Tables(null,{
view : this
});
this.field = new Fields(null,{
view : this
});
},
events : {
"click #choose" : "generate"
},
generate:function(){
var table = ( this.$("#table option:selected").text());
var dbname = ( this.$("#database").text());
var list_fields = new Field();
list_fields.urlRoot = list_fields.urlRoot+"/"+dbname+"/"+table;
list_fields.fetch({
success:function(){
console.log(JSON.stringify(list_fields));
}
});
this.field.add(list_fields);
},
getFields:function(model){
console.log(JSON.stringify(model));
}
});
var apprun = new app;
/* var data = new Fields();
data.url=data.url+"/some/data";
alert(data.url);
data.fetch();
var staff = new Table();
staff.fetch();
var field = new Field();*/
});
the problem is the context of "this". the success callback function has "this" set to the list_fields. you can work around this with a "self" or "that" variable:
generate:function(){
var table = ( this.$("#table option:selected").text());
var dbname = ( this.$("#database").text());
var list_fields = new Field();
list_fields.urlRoot = list_fields.urlRoot+"/"+dbname+"/"+table;
var that = this;
list_fields.fetch({
success:function(){
console.log(JSON.stringify(list_fields));
that.field.add(list_fields);
}
});
},
as a side note - your collections should never have a reference to a view. instead, your view should reference the collection and bind to the collection event
var Fields = Backbone.Collection.extend({
model:Field,
url:'http://localhost/campusfeed/index.php/welcome/generateFields',
});
var app = Backbone.View.extend({
initialize:function(model,options){
//Create collections in here
this.field = new Fields();
this.field.bind("add", this.getFields, this);
},
getFields: function(){ ... }
});

Resources