Backbone view is not getting displayed - backbone.js

I am a newbie to Backbone programming.
Why my collection is not being posted to the server?
var VisitModel = Backbone.Model.extend({
url: '/book',
defaults: {
"startTime" : ""
"visitType" : "Outsider"
}
});
var VisitCollection = Backbone.Collection.extend({
model: VisitModel,
urlRoot: '/visit'
});
In my view.js:
this.collection = new BookCollection();
this.model = new BookModel({"startTime" : new Date().getTime()});
this.collection.add(this.model);

You need to call this.collection.save() or no data is sent to the server.

Related

How To Change Backbone Dynamic URL with Backbone Events/Vent?

Edited This Below
In this image below I have two main regions.
One for the user list on the left: allusersRegion
And another for the the right side where a layout is displayed, which contains unique attributes to the user that was clicked in the allusersRegion and a list of articles by the user: middleCoreRegion
**If you noticed the middleCoreRegion is showing all articles by all users..This is wrong and I am trying to show all articles of the individual user (in this case. "kev")
I tried to see if my problem was with my JSON api (served via node/rest/mongoose) or with my underscore templates, but if it displays both list then I suppose I need to filter from inside backbone.
At first I tried using a Marionette.vent to simply change the url, but somhow I can't get the _id name into the url: function(), it says undefined...
var someuser = this.model.get("_id");
myApp.vent.trigger("showarticles", someuser);
I add a listener in the backbone collection on the same page:
myApp.vent.on("showarticles", someuser);
**The Edit (A Different Way of Doing this) Here is my code
var usertab = Poplive.module('usertab', {
startWithParent: true,
});
usertab.addInitializer(function() {
User = Backbone.Model.extend({});
UniqueArticle = Backbone.Model.extend({});
//Collections
Users = Backbone.Collection.extend({
model: User,
url: '/api/user2'
});
UniqueArticles = Backbone.Collection.extend({
model: UniqueArticle,
url: '/api/survey'
});
//Layout
var VisitingLayoutView = Backbone.Marionette.Layout.extend({
template: "#visiting-layout",
regions: {
firstRegion: "#listone",
secondRegion: "#listtwo",
thirdRegion: "#listthree",
playRegion: "#playhere",
articlesRegion: "#articleshere"
}
});
AllUserView = Backbone.Marionette.ItemView.extend({
template: "#tab-alluser-template",
tagName: 'li',
events: {
"click #openprofile" : "OpenProfile"
},
OpenProfile: function(){
console.log("Profile is open for " + this.model.get("username"));
var modelo = this.model.get("_id");
var vlv = new VisitingLayoutView({model: this.model});
Poplive.middleCoreRegion.show(vlv);
var ua = new UniqueArticles();
var uacoll = new UniqueArticlesView({collection: ua});
vlv.articlesRegion.show(uacoll);
}
})
//ItemViews
UniqueArticleView = Backbone.Marionette.ItemView.extend({
template: "#unique-article-template"
});
//CollectionViews
AllUsersView = Backbone.Marionette.CompositeView.extend({
template: "#tab-allusers-template",
itemView: AllUserView
});
UniqueArticlesView = Backbone.Marionette.CollectionView.extend({
template: "#unique-articles-template",
itemView: UniqueArticleView
});
//Render Views
var alluserview = new AllUserView();
var allusersview = new AllUsersView();
//Fetch Collections
var theusers = new Users();
theusers.fetch();
var userscoll = new AllUsersView({collection: theusers});
Poplive.allusersRegion.show(userscoll);
});
Assuming UniqueArticle to be the Backbone Model, for the Model with a specific id to be fetched you would need to define the urlRoot property which will append the id of the model to the request.
So the id attribute will be appended to the end of the request the model from the server when you do a fetch on it
var UniqueArticle = Backbone.Model.extend({
idAttribute : 'someuser',
urlRoot : function(someuser){
return '/api/visitingarticles/'
}
// this would send a request for
// /api/visitingarticles/someId
});
var UniqueArticles = Backbone.Collection.extend({
model: Article,
url : function(someuser){
return '/api/visitingarticles/'
}
// /api/visitingarticles -- All Articles will be fetched
});
I think what you want, is to define url as a function, and have a user attribute on your collection:
var UniqueArticles = Backbone.Collection.extend({
model: Article,
initialize: function(){
var self = this;
myApp.vent.on("showarticles", function(someuser){
self.user = someuser;
self.fetch();
}
},
url : function(){
var fragment = '/api/visitingarticles/';
if(this.user && this.user.id){
return fragment + this.user.id;
}
return fragment;
}
});
(Disclaimer: untested code, but it works in my head :D)
Then each time you trigger the event, the userattribute is updated, the collection is reset with the updated url.
As a side note, you might want to look into using a filtered collection. I've implemented that idea in my book, based on Derick Bailey's code here: http://jsfiddle.net/derickbailey/7tvzF/
Here is my version: https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/entities/common.js
And an example of its use (lines 38-41): https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/apps/contacts/list/list_controller.js#L38

backbone.js - Undefined is not a function

I've started learning Backbone.js and tried to write my first app with Collections. Here is the code:
console.clear();
(function($){
window.App = {
Models : {},
Collections : {},
Views : {}
};
//a single estimate
App.Models.Estimate = Backbone.Model.extend({});
// multiple esitmates
App.Collections.Estimates = Backbone.Collection.extend({
model : App.Collections.Estimate
});
App.Views.Estimates = Backbone.View.extend({
tagName: 'ul',
render : function(){
this.collection.each(this.addTo,this);
},
addTo:function(estimate){
var dir = App.Views.Estimate({model:estimate}).render();
this.$el.append(dir.el);
}
});
App.Views.Estimate = Backbone.View.extend({
tagName: 'li',
render :function(){
this.$el.html(this.model.get('title'));
return this;
}
});
var jSon = [{title:'Abhiram', estimate:8}];
var estimates = new App.Collections.Estimates(jSon);
console.log(estimates);
var tasksView = new App.Views.Estimates({collection:estimates});
// var a = tasksView.render().el;
//console.log(a);
})($j||jQuery);
I've all the three included :
jQuery first, Underscore next and Backbone. I keep getting "Undefined is not a function".Please let me know if i am doing anything wrong.
Thanks!
Are you sure that you want to assign collection App.Collections.Estimate as model to it self?
// multiple esitmates
App.Collections.Estimates = Backbone.Collection.extend({
model : App.Collections.Estimate
});

backbone.js each function not receiving the models

I am trying to receive a json data and append to element. all are work fine up to i use the static assignments. while i start to fetch the data from server side, or using fetch nothing work for me.. something wrong with my fech process, any can help me to correct my fetch process and update my code.(instead of simply placing the correct code)..
my JSON(sample):
nameing = [
{name:'student4'},
{name:'student5'},
{name:'student6'}
]
Backbone code:
(function($){
var list = {};
list.model = Backbone.Model.extend({
defaults:{
name:'need the name'
}
});
list.collect = Backbone.Collection.extend({
model:list.model,
url : 'data/names.json', //this is correct path.
initialize:function(){
this.fetch();
}
});
list.view = Backbone.View.extend({
initialize:function(){
this.collection = new list.collect();
this.collection.on("reset", this.render, this);
},
render:function(){
_.each(this.collection.models, function(data){
console.log(data); // i am not get any model here... any one correct my code?
})
}
});
var newView = new list.view();
})(jQuery)
thanks in advance.
Your JSON is not valid. Wiki
[
{"name":"student4"},
{"name":"student5"},
{"name":"student6"}
]

Empty backbone collection/model at working API?

i try to fetch a record of a rails-api (same host) into my backbone collection. i have the following code:
// Models
App.GeeksModel = Backbone.Model.extend({
urlRoot: "/geeks",
idAttribute: "id"
});
// Collections
App.GeeksCollection = Backbone.Collection.extend({
url: "/geeks",
model: App.GeeksModel
});
in my router i have the following
// Router
App.GeekRouter = Backbone.Router.extend({
routes: {
"": "index"
},
initialize: function() {
console.log("router - init");
},
index: function() {
console.log("route - index");
var geekCollection = new App.GeeksCollection();
var mapView = new App.GeeksMapView({ el: $("#foo"), model: geekCollection });
geekCollection.fetch();
}
});
when browsing the url, the view loads correctly and at the server i see, that one entry is fetched from the database. but as soon as i check the model length in my view using
this.model.length
the collection is empty... any advice on this?
thanks
EDIT 1:
when changing the index router method to
var mapView = new App.GeeksMapView({ el: $("#map"), collection: geekCollection });
and e.g. check for the collection length in the views intialize method
...
initialize: function() {
this.render();
console.log(this.collection.length);
},
...
it retunes 0 as well... so nothing changed!
I believe you want to do collection.length or if accessing from the model - each model holds reference to collection in which it was created model.collection.length - if this is referencing to collection doing just this.length should be enough, if it's a model then this.collection.length will do it for you.
Models have no property length so should always be undefined unless you define it yourself.

how to access a models data from a view in backbone.js

I have a model named person:
var person = Backbone.Model.extend({
initialize: function(){
console.log('cool');
},
defaults:{
names:['a','k','d','s','h','t']
}
})
Now I have a view:
var person_view = Backbone.View.extend({
model : person,
output: function(){
console.log(this.model.get('names'))
}
});
Created an object of the view:
var obj = new person_view()
Try to access names:
obj.output()
But I got this error:
TypeError: Object function (){ parent.apply(this, arguments); } has no method 'get'
Can you show me how to do things properly?I've only just started getting to know backbone.js so please bear with me.
You have to initialize your Model before you could access it :
var person_view = Backbone.View.extend({
initialize: function() {
this.model = new person();
},
output: function(){
console.log(this.model.get('names'))
}
});
Instead of passing the model when you extend the view, you'll want to pass it when you construct a new view:
var person_view = Backbone.View.extend({
output: function(){
console.log(this.model.get('names'))
}
});
var obj = new person_view({
model : new person()
});
Your "person_view" can not access any model (which is expected by that view) ,as no model is created yet, when you are declaring "person_view" and calling its function.
First make a model then pass it to view when declaring that "person_view".
var model_person_for_view= new person();
var obj = new person_view(model:model_person_for_view);
obj.output();

Resources