Backbone Nested Views & Nested Models - backbone.js

I am a newbie to backbone and trying to start using in our projects.
My requirement is I have something like this
var TextFields = Backbone.Model.extend({});
var TextFieldsCollection = Backbone.Collection.extend({});
var Module = Backbone.Model.extend({
defaults: {
fields: new TextFieldsCollection()
});
var ModuleCollection = Backbone.Collection.extend({
model: CTModule
});
Now I have views defined for TextFields & Modules.
If I change a value in TextFields a event gets fired for the model and I am changing the value in the model but the collection is not getting updated.
I tried to trigger backbone events in the child model but at the collection view I am not able to map to the correct model that triggered the change event.
Any comments are helpful. I am not in a position to use more libraries. Can this be done in Backbone?

I do not know what is full code, but if you do it in a fashion that Backbone apps are usually written everything should work.
Quick tutorial:
var TestModel = Backbone.Model.extend({});
var TestModelCollection = Backbone.Collection.extend({ model: TestModel });
// now if you have a view for collection
var TestModelCollectionView = Backbone.View.extend({
initialize: function(opts) {
this.collection = opts.collection;
this.collection.on('change', this.render, this) // so - rerender the whole view
}
});
//execution:
var modelData = { foo: 'bar' };
var collection = new TestModelCollection([modelData]);
var view = new TestModelCollectionView({collection: collection});
view.render();
collection.first().set('your_attr', 'new_value'); // will cause rerender of view
//////
One more thing - if you have collection, which is kept by the model (in your case Modules model, which have collection as one of its attributes), and your view keeps that model, you will have to either bind directly from view to collection via model (this.model.get('fields').on( .... )), or rethrow collection event in your model
I hope I helped at least a bit.
//////
There might be some syntax errors in my code - didn't run it on js fiddle.

Related

Marionette ItemView not re-rendering on model change from collection view

I have created a collection passing a collection view and a collection. The collection references a model I have created. when fetching the collection the items get rendered succesfully, but when the models change, the itemViews are not being re-rendered as expected.
for example, the itemAdded function in the tweetCollectionView is called twice ( two models are added on fetch ) but even though the parse function returns different properties over time for those models ( I assume this would call either a change event on the collection, or especially a change event on the model, which I have tried to catch in the ItemView ) the itemChanged is never called, and the itemViews are never re-rendered, which i would expect to be done on catching the itemViews model change events.
The code is as follows below:
function TweetModule(){
String.prototype.parseHashtag = function() {
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
var tag = t;
return "<span class='hashtag-highlight'>"+tag+"</span>";
});
};
String.prototype.removeLinks = function() {
var urlexp = new RegExp( '(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?' );
return this.replace( urlexp, function(u) {
var url = u;
return "";
});
};
var TweetModel = Backbone.Model.extend({
idAttribute: 'id',
parse: function( model ){
var tweet = {},
info = model.data;
tweet.id = info.status.id;
tweet.text = info.status.text.parseHashtag().removeLinks();
tweet.name = info.name;
tweet.image = info.image_url;
tweet.update_time_full = info.status.created_at;
tweet.update_time = moment( tweet.update_time_full ).fromNow();
return tweet;
}
});
var TweetCollection = Backbone.Collection.extend({
model: TweetModel,
url: function () {
return '/tweets/game/1'
}
});
var TweetView = Backbone.Marionette.ItemView.extend({
template: _.template( require('./templates/tweet-view.html') ),
modelEvents:{
"change":"tweetChanged"
},
tweetChanged: function(){
this.render();
}
})
var TweetCollectionView = Marionette.CompositeView.extend({
template: _.template(require('./templates/module-twitter-feed-view.html')),
itemView: TweetView,
itemViewContainer: '#tweet-feed',
collection: new TweetCollection([], {}),
collectionEvents: {
"add": "itemAdded",
"change": "itemChanged"
},
itemAdded: function(){
console.log('Item Added');
},
itemChanged: function(){
console.log("Changed Item!");
}
});
this.startInterval = function(){
this.fetchCollection();
this.interval = setInterval( this.fetchCollection, 5000 );
}.bind(this);
this.fetchCollection = function(){
this.view.collection.fetch();
this.view.render();
}.bind(this);
//build module here
this.view = new TweetCollectionView();
this.startInterval();
};
I may be making assumptions as to Marionette handles event bubbling, but according to the docs, I have not seen anything that would point to this.
Inside your CollectionView, do
this.collection.trigger ('reset')
after model have been added.
This will trigger onRender () method in ItemView to re-render.
I know I'm answering an old question but since it has a decent number of views I thought I'd answer it correctly. The other answer doesn't address the problem with the code and its solution (triggering a reset) will force all the children to re-render which is neither required nor desired.
The problem with OP's code is that change is not a collection event which is why the itemChanged method is never called. The correct event to listen for is update, which according to the Backbone.js catalog of events is a
...single event triggered after any number of models have been added
or removed from a collection.
The question doesn't state the version of Marionette being used but going back to at least version 2.0.0 CollectionView will intelligently re-render on collection add, remove, and reset events. From CollectionView: Automatic Rendering
When the collection for the view is "reset", the view will call render
on itself and re-render the entire collection.
When a model is added to the collection, the collection view will
render that one model in to the collection of child views.
When a model is removed from a collection (or destroyed / deleted),
the collection view will destroy and remove that model's child view
The behavior is the same in v3.

How does Chaplin.js handle passing a collection to a view?

I can create a simple model like so:
define(["models/base/model"], function(Model) {
"use strict";
var IssueModel = Model.extend({
defaults:{
lastName: "Bob",
firstName: "Doe"
}
});
return IssueModel;
});
And then from my controller I can do this:
this.model = new IssueModel();
And then when I create my view I can pass it my model like so:
this.view = new IssueView({model: this.model});
Finally, in my template I can successfully get properties on the model by doing this:
Hi {{firstName}} {{lastName}}
But when I define a collection using IssueModel and I try to pass the collection to my view (and not the model like I showed previously) I can't figure out how to reference the models in my Handlebars template:
var self = this;
this.collection = new IssueCollection();
this.collection.fetch({
success: function(collection) {
self.view = new IssueView({collection: collection});
console.log(self.collection);
},
error: function(collection, error) {
// The collection could not be retrieved.
}
});
I know fetch properly retrieves 5 models from my Parse.com backend because this is what I get on the console:
My question is this. I know Chaplin.js uses getTemplateData, but when I pass a model I don't have to do anything special in order to reference the properties in my view. How would I reference, specifically iterate, over the collection I passed to my view in my Handlebars template?
{{#each [Model in the collection I passed to the view]}}
{{title}}
{{/each}}
Chaplin will render a collection using a CollectionView, it's basicly an extention of a normal view that listens for changes in your collection and adds/removes subviews accordingly.
this.view = new IssueCollectionView({collection: this.collection});
Also there is no need to wait for success call when using a collection view since it will automaticly render every child item when data is added.

BB Marionette: best way to update a collection without re-rendering

I have a very simple page that shows a collection in a table. Above it theres a search field where the user enters the first name of users.
When the user types I want to filter the list down.
Edit: I have updated the code to show how the current compositeView works. My aim is to integrate a searchView that can _.filter the collection and hopefully just update the collection table.
define([
'marionette',
'text!app/views/templates/user/list.html',
'app/collections/users',
'app/views/user/row'
],
function (Marionette, Template, Users, User) {
"use strict"
return Backbone.Marionette.CompositeView.extend({
template: Template,
itemView: User,
itemViewContainer: "tbody",
initialize: function() {
this.collection = new Users()
this.collection.fetch()
}
})
})
Divide your template in a few small templates, this increases performance at the client side, you don't have problems with overriden form elements and you have more reuseable code.
But be aware of too much separation, cause more templates means more views and more code/logic.
You don't seem to be making use of CollectionView as well as you could be. If I were you I would separate the concerns between the search box and the search results. Have them as separate views so that when one needs to rerender, it doesn't effect the other.
This code probably won't work straight away as I haven't tested it. But hopefully it gives you some clue as to what ItemView, CollectionView, and Layout are and how they can help you remove some of that boiler plate code
//one of these will be rendered out for each search result.
var SearchResult = Backbone.Marionette.ItemView.extend({
template: "#someTemplateRepresentingEachSearchResult"
)};
//This collectionview will render out a SearchResult for every model in it's collection
var SearchResultsView = Backbone.Marionette.CollectionView.extend{
itemView: SearchResult
});
//This layout will set everything up
var SearchWindow = Backbone.Marionette.Layout.extend({
template: "#someTemplateWithASearchBoxAndEmptyResultsRegionContainer",
regions:{
resultsRegion: "#resultsRegion"
},
initialize: function(){
this.foundUsers = new Users();
this.allUsers = new Users();
this.allUsers.fetch({
//snip...
});
events: {
'keyup #search-users-entry': 'onSearchUsers'
},
onSearchUsers: function(e){
var searchTerm = ($(e.currentTarget).val()).toLowerCase()
var results = this.allUsers.filter(function(user){
var firstName = user.attributes.firstname.toLowerCase();
return firstName.match(new RegExp(searchTerm))
});
this.foundUsers.set(results); //the collectionview will update with the collection
},
onRender: function(){
this.resultsRegion.show(new SearchResultsView({
collection: this.foundUsers
});
}
});
I think the most important thing for you to take note of is how CollectionView leverages the Backbone.Collection that you provide it. CollectionView will render out an itemView (of the class/type you give it) for each model that is in it's collection. If the Collection changes then the CollectionView will also change. You will notice that in the method onSearchUsers all you need to do is update that collection (using set). The CollectionView will be listening to that collection and update itself accordingly

mass-write using a backbone collection

Using backbone.js, say I had a collection -- Albums
var albums_collection = new Backbone.Collection([
{artist:"dell the funky homosapien"},
{artist:"raffe"},
{artist:"wilson philips"},
{artist:"eddie murply"},
{artist:"jordotech"}
]);
And corresponding view
AlbumView = Backbone.View.extend({
render: function(){
$(this.el).html(this.model.get('artist') + "<br />");
return this;
}
});
Let's say, instead of just these 4 albums, I had 10k albums and I wanted to render them all. Most backbone tutorials would say you should loop through the collection and append to the dom one by one.
album_colleciton.each(addOne);
addOne:function(model){
var view = new AlbumView({model:model});
$("#albums_container").append(view.render().el):
}
However, it's come to my attention that writing to the DOM one by one like this might actually slow down performance... Is there some way to save each one of these to perhaps an array and mass update all at once? I've tried:
var arr = [];
_.each(this.collection.models, function(model){
var view = new AlbumView({model:model});
arr.push(view.render().el);
});
$("#albumbs_view").html(arr.join(''));
But the above results in a series of "HTMLdivElement"'s being rendered. Any idea how to do just one single instead of 1000 in this case?
make sure your view does NOT specify an "el". allow that to be create by backbone. then your render function can populate the view's el all day long without it manipulating the DOM. finally, when you're done, attach it to the DOM.
CollectionView = Backbone.View.extend({
render: function(){
var that = this;
this.collection.each(function(m){
var v = new SomeView({model: m});
v.render();
that.$el.append(v.$el);
});
}
});
cv = new CollectionView({collection: someCollection});
cv.render();
$("#whatever").html(cv.$el);
By the way, my Backbone.Marionette framework will make this even easier for you:
SomeView = Marionette.ItemView.extend({
// ...
});
AllTheViews = Marionette.CollectionView.extend({
itemView: SomeView
});
atv = new AllTheViews({collection: someCollection});
atv.render();
$("#whatever").html(atv.$el);
And then there's Regions which make stuffing the view in to the DOM even easier... A good place to start if you're interested in Marionette is Addy Osmani's Backbone Fundamentals book, and the chapter on Marionette.

Backbone JS How to add a new model to a view to automaticlly re-render template

I would like to attach a new model to a view and have the view re-render. I'm able to render the view in the first place, but I'm having trouble changing the data in that view to a new model.
my_model_1 = Backbone.Model.extend({});
my_model_2 = Backbone.Model.extend({});
my_view = Backbone.View.extend({
initialize : function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render : function(){
}
});
var view_instance = new my_view({ model: my_model_1 });
//Template gets rendered
try{
view_instance.changeModel(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.set(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.fetch(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.model = my_model_2;
}catch(e){console.log(e)};
//Template should get updated with data from model 2
Any advice?
The change event if fired when the data in your model has changed, in your case your view isn't "rerenering" because the data of it's model hasn't changed rather you just switched models. What you can do is manually trigger the change event after switching your view's model or call it's render method
For example
view_instance.model = my_model_2;
my_model_2.change();

Resources