Backbone + Firebase Collection - backbone.js

I'm building a little app and can't figure out why I'm getting an error when trying to add to a collection. Here's the code:
var PollCollection = Backbone.Firebase.Collection.extend({
model: Poll,
url: 'https://***.firebaseio.com/polls',
});
var Poll = Backbone.Model.extend({
defaults: {
title: 'title',
}
});
var pollCollection = new PollCollection();
pollCollection.create({title: "test"});
Any ideas? Thanks!

If I move the model up above the collection everything works fine

Related

Backbone view is not getting displayed

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.

how to pass backbone-forms form to Marionette region?

I'm trying to render a backbone-forms form in a Marionette region, but it isn't showing. However, if I append the el of the view to the body of the document, it appears.
Do you see anything I'm doing wrong here?
var searchForm = Backbone.Model.extend({
schema: {
title: { type: 'Select', options: ['title1', 'title2'] }
}
});
var searchFormView = new Backbone.Form({
model: searchForm
}).render();
mainLayout.menuRegion.show(searchFormView);
//also tried this: mainLayout.menuRegion.show(searchFormView.el);
//this one worked: $("body").append(searchFormView.el);
Please let me know if you have any suggestions.
In Marionette, you don't need to call render on a view instance. That is the source or error.
Try this
var searchFormView = new Backbone.Form({
model: searchForm
})
mainLayout.menuRegion.show(searchFormView);

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

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.

Fetch backbone collection fail from django-tastypie

I'm using backbone-tastypie from https://github.com/PaulUithol/backbone-tastypie, and I can't fetch a collection data.
Thats my code:
var User = Backbone.Model.extend({
url: '/api/v1/user'
});
var HoraExtra = Backbone.Model.extend({
url: '/api/v1/horasextra/'
});
var HorasExtra = Backbone.Collection.extend({
url: '/api/v1/horasextra/',
model: HoraExtra
});
var Horas = new HorasExtra();
var activeUser = new User();
var HorasExtraView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render");
},
render: function() {
var plantilla = Handlebars.compile($("#horas_extra_template").html());
var html = plantilla(Horas);
this.$el.html(html);
console.log(JSON.stringify(Horas));
}
});
var HorasExtraWidget = new HorasExtraView({el: $('#base')});
Horas.fetch({
data: {
"usuario__id": 2,
"hor_com__month": 11
}
});
HorasExtraWidget.render();
And that's the result of console.log(JSON.stringify(Horas):
[]
Many thanks
I would suggest to you that you take tastypie, backbone and build your own simple project in 1-2 days.
Then you will get to know basic issues of coupling those 2 frameworks.
Without that knowledge it is pointless you try out other people's projects and then wonder "what isn't working".
And from my personal experience, both tastypie and javascript are pretty straightforward and are easy to couple.
And I am NOT an expert.
couple of points: try explicitly fetching models with fetch, manipulate fetched model from success callback, and watch your model url's, forward slashes in them etc.
Seems your collection is empty.
See in console if there is a GET call to server.
If not, you're not actually fetching anything from the server.
I used https://github.com/amccloud/backbone-tastypie and then your code should look like this, I guess. Not tested.
var HorasCollection = Backbone.Tastypie.Collection.extend({
url: '/api/v1/horasextra/'
});
var HorasExtraView = Backbone.View.extend({
el: $('#base'),
entries: new HorasCollection(),
render: function() {
var that = this;
this.entries.fetch({
success: function(entries){
console.log("Entries", entries.models);
// var t = _.template(template, {hello: 'world'});
// that.$el.html(t);
},
error: function(model, response){
console.log("Error", response);
}
});
}
});
If you're trying to create a table for your data, try my jquery plugin :)
https://github.com/sspross/tastybackbonepie

Resources