Backbone.Paginator infinite mode, with Marionette - javascript

In my Marionette app, I have a Collection view, with a childView for it's models.
The collection assigned to the CollectionView is a PageableCollection from Backbone.paginator. The mode is set to infinite.
When requesting the next page like so getNextPage(), the collection is fetching data and assigning the response to the collection, overwriting the old entries, though the full version is store in collection.fullCollection. This is where I can find all entries that the CollectionView needs to render.
Marionette is being smart about collection events and will render a new childView with it's new model when a model is being added to the collection. It will also remove a childView when it's model was removed.
However, that's not quite what I want to do in this case since the collection doesn't represent my desired rendered list, collection.fullCollection is what I want to show on page.
Is there a way for my Marionette view to consider collection.fullCollection instead of collection, or is there a more appropriate pagination framework for Marionette?
Here's a fiddle with the code
For those who don't like fiddle:
App = Mn.Application.extend({});
// APP
App = new App({
start: function() {
App.routr = new App.Routr();
Backbone.history.start();
}
});
// REGION
App.Rm = new Mn.RegionManager({
regions: {
main: 'main',
buttonRegion: '.button-region'
}
});
// MODEL
App.Model = {};
App.Model.GeneralModel = Backbone.Model.extend({});
// COLLECTION
App.Collection = {};
App.Collection.All = Backbone.PageableCollection.extend({
model: App.Model.GeneralModel,
getOpts: function() {
return {
type: 'POST',
contentType: 'appplication/json',
dataType: 'json',
data: {skip: 12},
add: true
}
},
initialize: function() {
this.listenTo(Backbone.Events, 'load', (function() {
console.log('Load more entries');
// {remove: false} doesn't seem to affect the collection with Marionette
this.getNextPage();
})).bind(this)
},
mode: "infinite",
url: "https://api.github.com/repos/jashkenas/backbone/issues?state=closed",
state: {
pageSize: 5,
firstPage: 1
},
queryParams: {
page: null,
per_page: null,
totalPages: null,
totalRecords: null,
sortKey: null,
order: null
},
/*
// Enabling this will mean parseLinks don't run.
sync: function(method, model, options) {
console.log('sync');
options.contentType = 'application/json'
options.dataType = 'json'
Backbone.sync(method, model, options);
}
*/
});
// VIEWS
App.View = {};
App.View.MyItemView = Mn.ItemView.extend({
template: '#item-view'
});
App.View.Button = Mn.ItemView.extend({
template: '#button',
events: {
'click .btn': 'loadMore'
},
loadMore: function() {
Backbone.Events.trigger('load');
}
});
App.View.MyColView = Mn.CollectionView.extend({
initialize: function() {
this.listenTo(this.collection.fullCollection, "add", this.newContent);
this.collection.getFirstPage();
},
newContent: function(model, col, req) {
console.log('FullCollection length:', this.collection.fullCollection.length, 'Collection length', this.collection.length)
},
childView: App.View.MyItemView
});
// CONTROLLER
App.Ctrl = {
index: function() {
var col = new App.Collection.All();
var btn = new App.View.Button();
var colView = new App.View.MyColView({
collection: col
});
App.Rm.get('main').show(colView);
App.Rm.get('buttonRegion').show(btn);
}
};
// ROUTER
App.Routr = Mn.AppRouter.extend({
controller: App.Ctrl,
appRoutes: {
'*path': 'index'
}
});
App.start();

You could base the CollectionView off the full collection, and pass in the paged collection as a separate option:
App.View.MyColView = Mn.CollectionView.extend({
initialize: function(options) {
this.pagedCollection = options.pagedCollection;
this.pagedCollection.getFirstPage();
this.listenTo(this.collection, "add", this.newContent);
},
// ...
}
// Create the view
var colView = new App.View.MyColView({
collection: col.fullCollection,
pagedCollection: col
});
Forked fiddle

Related

Wrong backbone collection length. Can't each this collection

Sorry for my bad English. Tell me why the following happens:
I have some backbone collection:
var Background = window.Models.Background = Backbone.Model.extend({});
var Backgrounds = window.Models.Backgrounds = Backbone.Collection.extend({
model: window.Models.Background,
url: '/backgrounds/',
initialize: function() {
this.fetch({
success: this.fetchSuccess(this),
error: this.fetchError
});
},
fetchSuccess: function( collect_model ) {
new BackgroundsView ({ collection : collect_model });
},
fetchError: function() {
throw new Error("Error fetching backgrounds");
}
});
And some view:
var BackgroundsView = window.Views.BackgroundsView = Backbone.View.extend({
tagName: 'div',
className: 'hor_slider',
initialize: function() {
this.render();
},
render: function() {
console.log(this.collection);
this.collection.each( function (background) {
console.log(background);
//var backgroundView = new BackgroundView ({ model: background });
//this.$el.append(backgroundView.render().el);
});
}
});
now i creating collection
var backgrounds = new Models.Backgrounds();
but when I must render this view, in the process of sorting the collection its length is 0, but should be two. This log I see at console. How is this possible? What am I doing wrong??
You are creating the view before the collection fetch is successfull. Your code should be:
initialize: function() {
this.fetch({
success: this.fetchSuccess,
//------------------------^ do not invoke manually
error: this.fetchError
});
},
fetchSuccess: function(collection, response) {
new BackgroundsView ({ collection : collection});
},
You should let backbone call fetchSuccess when the fetch succeeds. Right now you're invoking the funcion immediately and passing the return value undefined as success callback.
This looks like a wrong pattern. Your data models shouldn't be aware of/controlling the presentation logic.
You have a view floating around without any reference to it. You should be creating a view instance with reference(for example from a router, or whatever is kick starting your application) and passing the collection to it. Then fetch the collection from it's initialize method and render after the fetch succeeds. Collection can be referenced via this.collection inside view.
Alternatively you can fetch the collection from router itself and then create view instance. Either way collection/model shouldn't be controlling views.
If the code is structured in the following way, the problem is solved. It was necessary to add a parameter reset to fetch.
var Background = window.Models.Background = Backbone.Model.extend({});
var Backgrounds = window.Models.Backgrounds = Backbone.Collection.extend({
model: window.Models.Background,
url: '/backgrounds/',
initialize: function() {
this.fetch({
reset : true,
});
}
});
var BackgroundsView = window.Views.BackgroundsView = Backbone.View.extend({
tagName: 'div',
className: 'hor_slider',
initialize: function() {
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
this.collection.each( function (background) {
var backgroundView = new BackgroundView ({ model: background });
this.$el.append(backgroundView.render().el);
}, this);
$('#view_list').empty();
$('#view_list').append(this.$el);
return this;
}
});

Backbone collection fetch render runs twice with router on first load

I am fairly new to Backbone and am trying to get my head around routers and calling a collection from a database.
I have the following
Collection:
var Scorecards = Backbone.Collection.extend({
model:Scorecard,
url:"http://localhost:3002/api/scorecards",
initialize:function(){
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
},
fetchSuccess: function (collection, response) {
console.log("results");
if(collection.length>0) {
var view = new ScorecardsView({el:'#scorecards-container', model:scorecards});
view.render();
}
else{
var view = new NoScorecardsView({el:'#scorecards-container'});
view.render();
}
},
fetchError: function(collection, response) {
throw new Error("Failed to get scorecards");
}
});
Router:
var ScorecardRouter = Backbone.Router.extend ({
routes: {
'' : 'home',
'create': 'createScorecard',
'edit': 'editScorecard'
},
home: function () {
console.log("Home view");
var view = new ScorecardsView({el:'#scorecards-container', model:scorecards});
view.render();
},
createScorecard: function () {
console.log('Create view');
var view = new CreateScorecardView({el:'#scorecards-container'});
view.render();
}
});
Scorecards view:
var ScorecardsView = Backbone.View.extend({
initialize: function(){
this.model.on('destroy', this.render, this);
},
render: function() {
console.log("Scorecard render");
var self = this;
this.$el.html(ScorecardContTemp);
this.model.each(function(scorecard){
var scorecardView = new ScorecardView({model:scorecard});
self.$('.scorecards-items tbody').append(scorecardView.render().$el);
});
},
events: {
"click #scorecard-create-btn" : "createScorecardView",
},
createScorecardView: function(e) {
e.preventDefault();
scorecardRouter.navigate('create', {trigger: true});
}
});
and I start things off with this
var scorecards = new Scorecards;
var scorecardRouter = new ScorecardRouter();
Backbone.history.start();
My problem is, when I first hit the home route, I'm getting the view render function running twice. Because firstly the fetch is calling it and also the route is calling it.
I need to remove the call from either the fetch success or the route, but when I do I get no results on initial load and I have to navigate to a different route and back to.
How are you supposed to achieve this? So I can fetch the results once and then display them via the route the fetch is successful but also show them in the route when a user navigates to it.
I hope that makes sense?
Any help would be great.
First of all, your data shouldn't know how it is rendered, so new View() anywhere within a Model or a Collection is a sure sign of a problem. Your views should watch their data and update themselves.
Your other possible source of confusion is passing {trigger: true} to your router navigate method. What kind of trouble that brings is elaborately explained in this classic Backbone article: Don’t Execute A Backbone.js Route Handler From Your Code.
For now, you definitely should remove the view rendering from the collection. Instead, your view should be aware of the collection and update itself when the data changes.
Here's an example of how I would setup my view to watch the collection:
/** Scorecard model */
var Scorecard = Backbone.Model.extend({
defaults: {
name: '',
email: ''
}
});
/** Scorecard View (I know it totally doesn't look like a scorecard, just an example view) */
var ScorecardView = Backbone.View.extend({
template: _.template('<%=name%>, <em><%=email%></em>'),
render: function(){
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
});
/** Collection */
var Scorecards = Backbone.Collection.extend({
model: Scorecard,
/** using fake api for the sake of this example to work */
url: "http://jsonplaceholder.typicode.com/users",
initialize:function(){
this.fetch({
success: this.fetchSuccess,
error: this.fetchError
});
},
fetchSuccess: function (collection, response) {
console.log("results:", collection);
},
fetchError: function(collection, response) {
throw new Error("Failed to get scorecards");
}
});
/** Scorecards view: */
var ScorecardsView = Backbone.View.extend({
initialize: function(){
this.collection.on('destroy', this.render, this);
/** render one added item whenever it comes to collection */
this.collection.on('add', this.addOne, this);
},
render: function() {
console.log("Scorecard render");
/** clean the items container,
which will be useful when items get destroyed
and we'll want to re-render whole collection */
this.$el.find('.scorecards-items').empty();
/** in case collection already has data, let's render it */
this.collection.each(this.addOne, this);
},
addOne: function(scorecard){
var scorecardView = new ScorecardView({ model: scorecard });
this.$('.scorecards-items').append(scorecardView.render().$el);
}
});
/** Router: */
var ScorecardRouter = Backbone.Router.extend ({
routes: {
'' : 'home'
},
home: function () {
console.log("Home view");
var view = new ScorecardsView({
el:'#scorecards-container',
collection: scorecards
});
view.render();
}
});
/** starting things off */
var scorecards = new Scorecards();
var scorecardRouter = new ScorecardRouter();
Backbone.history.start();
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
<div id="scorecards-container">
<div class="scorecards-items"></div>
</div>

Backbone: how to get and display just one model data in a view via router

I have created a very basic backbone app, to understand how it works.
In the router, I just wanna display just 1 model, i.e. a user, not the whole collection, by passing an id in the url, how to do that?
For example, I'd like to do someapp.com/app/#user/2, and this would display just user no2 details.
Please see my work in jsfiddle
// router
var ViewsRouter = Backbone.Router.extend({
routes: {
'': 'viewOne',
'one': 'viewOne',
'two': 'viewTwo',
'user/:id': 'user'
},
viewOne: function() {
var view = new TheViewOne({ model: new TheModel });
},
viewTwo: function() {
var view = new UserView({ model: new TheModel });
},
user: function(id) {
// how to get just 1 user with the corresponding id passed as argument
// and display it???
}
});
Many thanks.
https://github.com/coding-idiot/BackboneCRUD
I've written a complete Backbone CRUD with no backend stuff for beginners. Below is the part where we get the user from the collection and show/render it.
View
var UserEditView = Backbone.View.extend({
render: function(options) {
if (options && options.id) {
var template = _.template($("#user-edit-template").html(), {
user: userCollection.get(options.id)
});
this.$el.html(template);
} else {
var template = _.template($("#user-edit-template").html(), {
user: null
});
// console.log(template);
this.$el.html(template);
}
return this;
},
Router
router.on('route:editUser', function(id) {
console.log("Show edit user view : " + id);
var userEditView = new UserEditView({
el: '.content'
});
userEditView.render({
id: id
});
});
Update
Particularly, sticking to your code, the router will look something like this :
user: function(id) {
var view = new UserView({ model: userCollection.get(id) });
}

How do i stop a single model adding his id to url in Backbone?

i have a problem with backbone.js. I'm creating a frontend for an existing api, for me unaccessable. The problem is that when I try to add a new model to a collection, i can see in my firebug that every time backbone tries to create the model it appends the attribute name to the url.
Example:
default url = /api/database
when i perform a GET = /api/database
when i perform a GET/POST with object {"name": "test"} =
/api/database/test is the result
Anyone knows how to avoid that behaviour?
Greetings Kern
My View:
window.databaseView = Backbone.View.extend({
el: '#content',
template: new EJS({url: 'js/templates/databaseView.ejs'}),
initialize: function() {
var self = this;
this.collection.fetch({
success: function() {
console.log(self.collection);
var test = self.collection.get("_system");
console.log(test);
self.collection.get("_system").destroy();
self.collection.create({name: "test"});
}
});
},
render: function(){
$(this.el).html(this.template.render({}));
return this;
}
});
Model:
window.Database = Backbone.Model.extend({
initialize: function () {
'use strict';
},
idAttribute: "name",
defaults: {
}
});
Collection:
window.ArangoDatabase = Backbone.Collection.extend({
model: window.Database,
url: function() {
return '../../_api/database/';
},
parse: function(response) {
return _.map(response.result, function(v) {
return {name:v};
});
},
initialize: function() {
this.fetch();
},
getDatabases: function() {
this.fetch();
return this.models;
},
dropDatabase: function() {
},
createDatabse: function() {
}
});
By default, Backbone create models URLs this way: {collection url}/{model id}.
It consider the collection URL to be a base URL in a RESTful way.
Here you only want to set the Model url property to the URL you whish to call. That'll overwrite the default behavior. http://backbonejs.org/#Model-url

backbone.js collection usage

I'm running into a problem maintaining my collection. First, I load attendees into a collection via fetch. This loads existing attendees from the database in to the collection. I also have a button which allows a user to add new attendees. When an attendee is manually entered it seems to wipe out the models loaded into the collection via fetch and starts fresh. All manually added attendees now populate the collection; however, i would like both the fetch loaded and manually added attendees to populate this list.
var InviteeView = Backbone.View.extend({
tagName: "tr",
initialize: function() {
this.collection = new InviteeJSONList();
_.bindAll(this, 'render','appendItem','remove','saveInvitee');
},
events: {
"click .removeInvitee":"remove",
"click .saveInvitee":"saveInvitee"
},
render: function() {
var source = $("#invitee-template").html();
var template = Handlebars.compile(source);
var context = inviteeListJSON.attributes['json'];
var html=template(context);
$(this.el).html(html);
return this;
},
appendItem: function() {
$("#attendees").append(this.render().el);
},
remove: function() {
$(this.el).remove();
},
saveInvitee: function() {
var value = $(this.el).find('select').val();
var model = this.collection.attributes['json']['invitees'];
model = model.filter(function(attributes) {return attributes.encrypted_id==value});
var attendee = new Attendee({
user_id: model[0]['id'],
meeting_id: '<?=$mid?>',
status: 'Uncomfirmed',
first_name: model[0]['first_name'],
last_name: model[0]['last_name'],
email: model[0]['email'],
user_uuid: model[0]['encrypted_id'],
unavailable_dates: model[0]['unavailable_dates']
});
attendeeView.addAttendeeItem(attendee.attributes)
this.remove();
}
});
var AttendeeList = Backbone.Collection.extend({
model: Attendee,
url: '<?=$baseURL?>api/index.php/attendees/<?=$mid?>&timestamp=<?=$timestamp?>&userid=<?=$userid?>&apikey=<?=$apikey?>',
parse: function(response) {
if(response!="No History") {
$.each(response['attendees'], function(key, value) {
attendeeView.addAttendeeItem(value);
});
$('.loading_attendees').hide();
}
else {
$('.loading_attendees').html("No attendees exists for this meeting.");
}
}
});
var AttendeeView = Backbone.View.extend({
el: $('body'),
initialize: function() {
_.bindAll(this, 'render','fetchAttendees', 'appendItem', 'addAttendeeItem');
this.counter=0;
this.collection = new AttendeeList();
this.collection.bind('add', this.appendItem);
this.fetchAttendees();
},
events: {
"click #addInvitee":"appendInvitees",
},
appendInvitees: function() {
var inviteeView = new InviteeView();
inviteeView.appendItem();
},
render: function() {
},
fetchAttendees: function() {
this.collection.fetch({
success: function(model, response) {
},
error: function(model, response) {
$('#loading_attendees').html("An error has occurred.");
}
});
},
appendItem: function(item) {
var attendeeItemView = new AttendeeItemView({
model: item
});
$("#attendees").append(attendeeItemView.render().el);
attendeeItemView.updateAttendeeStatusSelect();
},
addAttendeeItem: function(data) {
this.counter++;
var attendee = new Attendee({
id: data['id'],
user_id: data['user_id'],
meeting_id: data['id'],
status: data['status'],
comments: data['comments'],
attended: data['datetime'],
first_name: data['first_name'],
last_name: data['last_name'],
email: data['email'],
counter: this.counter,
user_uuid: data['user_uuid'],
unavailable_dates: data['unavailable_dates']
});
this.collection.add(attendee);
},
});
After the collection (2 items loaded from REST API) is loaded via fetch():
console.log(this.collection.models) outputs:
[d]
[d,d]
Then when I manually add an attendee via a button the collection seems to reset:
console.log(this.collection.models) outputs:
[d]
Good that it's working, as there are many ways to go. I probably would have structured it a bit differently to leverage the Backbone methods that instantiate modes, but working code is the real goal, so these are just my thoughts:
Rather than actually instantiate the Models in the Collection parse() method, merely have parse return an array of data objects from which Backbone would instantiate the models, and trigger a
Rather than call fetch for the Collection inside AttendeeView, but outside the View class
Either have AttendeeView represent the view for a single attendee, or name it AttendeeListView and have it render the list
For instance:
AttendeeList = Backbone.Collection.extend({
...
parse: function(response) {
// create an array of objects from which the models can be parsed
var rawItems = [];
$.each(response['attendees'], function(key, value) {
rawItems.push({
id: data['id'],
user_id: data['user_id'],
meeting_id: data['id'],
status: data['status'],
comments: data['comments'],
attended: data['datetime'],
first_name: data['first_name'],
last_name: data['last_name'],
email: data['email'],
counter: this.counter,
user_uuid: data['user_uuid'],
unavailable_dates: data['unavailable_dates']
});
});
return rawItems;
},
...
}
and then either use the success/failure call backs:
AttendeeList.fetch( onListFetchSuccess , onListFetchFail );
or listen for the reset event that gets triggered:
AttendeeList.on('reset', createAttendeeListView );
(I didn't actually edit and run the code, this is just an outline)
I ended up resolving the issue by removing the url parameter and parse function out of the collection and into the view. Now everything works as expected.

Categories

Resources