What's the model, controller, view in the following backbone.js example? - javascript

I got this code:
(function($){
var ListView = Backbone.View.extend({
el: $('body'), // el attaches to existing element
events: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here
this.counter = 0; // total number of items added thus far
this.render();
},
render() now introduces a button to add a new list item.
render: function(){
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
},
addItem(): Custom function called via click event above.
addItem: function(){
this.counter++;
$('ul', this.el).append("<li>hello world"+this.counter+"</li>");
}
});
var listView = new ListView();
})(jQuery);
from this tutorial.
I understand that Backbone.js introduces a MVC pattern to the front end.
But in the code above I can't see that.
Can anyone explain that to me?

There is technically no controller in backbone.js. The main structures are Models, Views, Collections (that act as arrays and contain lots of models), and Routers.
The link you listed - http://arturadib.com/hello-backbonejs/ - is probably the best way to learn Backbone.js - especially with little background in Javascript. So you are on the right track. That project is a direct lead-in to the backbone.js ToDo list tutorial: http://documentcloud.github.com/backbone/docs/todos.html
This site will also explain things at a more basic level - I found it very helpful: http://backbonetutorials.com/

That's just the view part code. See other .js files in the same tutorial. Better check out all the files from 1.js to 5.js
Better check it from first: Hello Backbone

Note that Backbone View isn't the one you expected in MVC its more like a controller or the presenter in MVP. Here is a nice article that describes this differences.

Related

How do JS frameworks bind model to a view?

I've been diving into the scary stuff recently.. :) scary stuff being the source of popular js frameworks like backbone.js, angular.js, vue.js and so on.
I'll take Backbone as an example here. I am trying to figure out how is a model attached to the view?
Here is the code and if someone could just point out the part where this is happening, would be awesome!
https://github.com/jashkenas/backbone/blob/master/backbone.js
Actually, the part I don't understand is that there is not innerHTML called anywhere, so how is the element being populated with the data?
Backbone is not Angular, it doesn't bind model to html for you, also it does not actually renders views for you, you have to implement render methods in your views and call them when you find appropriate. In fact, I think it might be confusing to developer coming from 2-way binding frameworks. Backbone is all about giving all the control to the developer, but you have to do all the work yourself.
Minimal model => view flow example would be something like
var MyModel = Backbone.Model.extend({
defaults: {
test: 'test',
},
initialize: function (options) {
console.log(this.get('test'));
},
});
var MyView = Backbone.View.extend({
el: '#your-el',
initialize: function (options) {
this.template = _.template('<div><%= test %></div>');
this.listenTo(this.model, 'change', this.render);
},
render: function () {
// rendering happens here, innerHTML, $.html(), whichever you prefer
// and you can pass model data as this.model.toJSON()
// or you can pass an object with data
// also, you probably will need a templating library or use
// bundled underscore _.template(html, data) method to render blocks of html
// for example, with underscore
this.$el.html(this.template(this.model.toJSON()));
return this; // for chaining
},
});
var myModel = new MyModel();
var myView = new MyView({
model: myModel,
});
myModel.set('test', 'newValue'); // view should render after this call
Check the list of built-in events at backbonejs.org.

Why is Backbone.js looking for the template before I render the view?

I'm new to Backbone.js and I'm writing a small app. I decided to structure everything related to each resource (books, authors) in separate files (books.js, authors.js). Each file features four BBjs classes: a model, a collection, a model view and a collection view corresponding to the given resource. This was working fine when only one of this files was to be included.
Now I'm working on a screen that should show a book collection in a specific author page. I do not intend to render any of the author views, but only to use the author model. However, Backbone is failing with Uncaught TypeError: Cannot read property 'replace' of undefined (underscore.js) because it's looking for a template that's not present on this page.
My author view class looks like this:
app.AuthorView = Backbone.View.extend({
...
template: _.template( $('#book-table-row-template').html() ),
...
render: function(e) { ... }
});
The page does not feature any #book-table-row-template element (I guess that's what triggering the error) but I'm not even instantiating this view. What am I doing wrong? Is there any other more productive way to organize my backbone classes?
You are calling the _.template function right away. It doesn't wait for instantiation. And if there is no #book-table-row-template, jQuery will not find that either.
If you want it to wait until instantiation, set this.template in your initialize method, like so:
initialize: function() {
this.template = _.template( $('#book-table-row-template').html() );
}

Backbone: How do I put a collection inside a view

I see many tutorials which don't follow the supposedly best practice of making a model, a view and collection for that model then a view for the collection. Which would be the parent view?
How do I make a view for a collection? Also, is it possible for it to keep track of when a model is added or deleted for it to update/re-render?
You must do something like this in your collection view:
var view = Backbone.View.extend({});
var myView = new view({'collection' : new collection});
To handle add/remove event, use this in your initialize function:
this.collection.on("add", this.onAdd, this);
this.collection.on("remove", this.onRemove, this);
and in your model view:
this.model.on("change", this.onUpdate,this);
See it here: http://www.neiker.com.ar/backbone/
(Sorry, I don't speak english)
EDIT: Just use marionette:
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md

BackboneJS Rendering Problems

For the last six months I've been working with Backbone. The first two months were messing around, learning and figuring out how I want to structure my code around it. The next 4 months were pounding away a production-fit application. Don't get me wrong, Backbone has saved me from the thousands-lines mess of client side code that were the standard before, but it enabled me to do more grandiose things in less time, opening up a complete new stack of problems. For all the questions I raise here there are simple solutions that feels like hacks or just feel wrong. I promise a 300 points bounty for an awesome solution. Here goes:
Loading - For our use case (an admin panel) pessimistic syncing is bad. For some things I need to validate things on the server before accepting them. We started out before the 'sync' event was merged into Backbone,
and we used this little code for mimicking the loading event:
window.old_sync = Backbone.sync
# Add a loading event to backbone.sync
Backbone.sync = (method, model, options) ->
old_sync(method, model, options)
model.trigger("loading")
Great. It works as expected but it doesn't feel correct. We bind this event to all the relevant views and display a loading icon until we receive a success or error event from that model. Is there a better, saner, way to do this?
Now for the hard ones:
Too many things render themselves too much - Let's say our application have tabs. Every tab controls a collection. On the left side you get the collection. You click a model to start editing it at the center. You change its name and press tab to get to the next form item. Now, your app is a "real time something something" that notices the difference, runs validations, and automatically sync the change to the server, no save button required! Great, but the H2 at the start of the form is the same name as in the input - you need to update it. Oh, and you need to update the name on the list to the side. OH, and the list sorts itself by names!
Here's another example: You want to create a new item in the collection. You press the "new" button and you start filling out the form. Do you immediately add the item to the collection? But what happens if you decided to discard it? Or if you save the entire collection on another tab? And, there's a file upload - You need to save and sync the model before you can start uploading the file (so you can attach the file to the model). So everything starts rendering in tremors: You save the model and the list and the form renders themselves again - it's synced now, so you get a new delete button, and it shows in the list - but now the file upload finished uploading, so everything starts rendering again.
Add subviews to the mix and everything starts looking like a Fellini movie.
It's subviews all the way down - Here's a good article about this stuff. I could not, for the love of everything that is holy, find a correct way to attach jQuery plugins or DOM events to any view that has subviews. Hell ensues promptly. Tooltips hear a render coming a long and start freaking around, subviews become zombie-like or do not respond. This is the main pain points as here actual bugs stand, but I still don't have an all encompassing solution.
Flickering - Rendering is fast. In fact, it is so fast that my screen looks like it had a seizure. Sometimes it's images that has to load again (with another server call!), so the html minimizes and then maximizes again abruptly - a css width+height for that element will fix that. sometimes we can solve this with a fadeIn and a fadeOut - which are a pain in the ass to write, since sometimes we're reusing a view and sometimes creating it anew.
TL;DR - I'm having problems with views and subviews in Backbone - It renders too many times, it flickers when it renders, subviews detach my DOM events and eat my brains.
Thank you!
More details: BackboneJS with the Ruby on Rails Gem. Templates using UnderscoreJS templates.
Partial rendering of views
In order to minimize the full rendering of your DOM hierarchy, you can set up special nodes in your DOM that will reflect updates on a given property.
Let's use this simple Underscore template, a list of names:
<ul>
<% _(children).each(function(model) { %>
<li>
<span class='model-<%= model.cid %>-name'><%= model.name %></span> :
<span class='model-<%= model.cid %>-name'><%= model.name %></span>
</li>
<% }); %>
</ul>
Notice the class model-<%= model.cid %>-name, this will be our point of injection.
We can then define a base view (or modify Backbone.View) to fill these nodes with the appropriate values when they are updated:
var V = Backbone.View.extend({
initialize: function () {
// bind all changes to the models in the collection
this.collection.on('change', this.autoupdate, this);
},
// grab the changes and fill any zone set to receive the values
autoupdate: function (model) {
var _this = this,
changes = model.changedAttributes(),
attrs = _.keys(changes);
_.each(attrs, function (attr) {
_this.$('.model-' + model.cid + '-' + attr).html(model.get(attr));
});
},
// render the complete template
// should only happen when there really is a dramatic change to the view
render: function () {
var data, html;
// build the data to render the template
// this.collection.toJSON() with the cid added, in fact
data = this.collection.map(function (model) {
return _.extend(model.toJSON(), {cid: model.cid});
});
html = template({children: data});
this.$el.html(html);
return this;
}
});
The code would vary a bit to accommodate a model instead of a collection.
A Fiddle to play with http://jsfiddle.net/nikoshr/cfcDX/
Limiting the DOM manipulations
Delegating the rendering to the subviews can be costly, their HTML fragments have to be inserted into the DOM of the parent.
Have a look at this jsperf test comparing different methods of rendering
The gist of it is that generating the complete HTML structure and then applying views is much faster than building views and subviews and then cascading the rendering. For example,
<script id="tpl-table" type="text/template">
<table>
<thead>
<tr>
<th>Row</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% _(children).each(function(model) { %>
<tr id='<%= model.cid %>'>
<td><%= model.row %></td>
<td><%= model.name %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
var ItemView = Backbone.View.extend({
});
var ListView = Backbone.View.extend({
render: function () {
var data, html, $table, template = this.options.template;
data = this.collection.map(function (model) {
return _.extend(model.toJSON(), {
cid: model.cid
});
});
html = this.options.template({
children: data
});
$table = $(html);
this.collection.each(function (model) {
var subview = new ItemView({
el: $table.find("#" + model.cid),
model: model
});
});
this.$el.empty();
this.$el.append($table);
return this;
}
});
var view = new ListView({
template: _.template($('#tpl-table').html()),
collection: new Backbone.Collection(data)
});
http://jsfiddle.net/nikoshr/UeefE/
Note that the jsperf shows that the template can be be split into subtemplates without too much penalty, which would allow you to provide a partial rendering for the rows.
On a related note, don't work on nodes attached to the DOM, this will cause unnecessary reflows. Either create a new DOM or detach the node before manipulating it.
Squashing zombies
Derick Bailey wrote an excellent article on the subject of eradicating zombie views
Basically, you have to remember that when you discard a view, you must unbind all listeners and perform any additional cleanup like destroying the jQuery plugin instances. What I use is a combination of methods similar to what Derick uses in Backbone.Marionette:
var BaseView = Backbone.View.extend({
initialize: function () {
// list of subviews
this.views = [];
},
// handle the subviews
// override to destroy jQuery plugin instances
unstage: function () {
if (!this.views) {
return;
}
var i, l = this.views.length;
for (i = 0; i < l; i = i + 1) {
this.views[i].destroy();
}
this.views = [];
},
// override to setup jQuery plugin instances
stage: function () {
},
// destroy the view
destroy: function () {
this.unstage();
this.remove();
this.off();
if (this.collection) {
this.collection.off(null, null, this);
}
if (this.model) {
this.model.off(null, null, this);
}
}
});
Updating my previous example to give the rows a draggable behavior would look like this:
var ItemView = BaseView.extend({
stage: function () {
this.$el.draggable({
revert: "invalid",
helper: "clone"
});
},
unstage: function () {
this.$el.draggable('destroy');
BaseView.prototype.unstage.call(this);
}
});
var ListView = BaseView.extend({
render: function () {
//same as before
this.unstage();
this.collection.each(function (model) {
var subview = new ItemView({
el: $table.find("#" + model.cid),
model: model
});
subview.stage();
this.views.push(subview);
}, this);
this.stage();
this.$el.empty();
this.$el.append($table);
return this;
}
});
http://jsfiddle.net/nikoshr/yL7g6/
Destroying the root view will traverse the hierarchy of views and perform the necessary cleanups.
NB: sorry about the JS code, I'm not familiar enough with Coffeescript to provide accurate snippets.
Ok, in order.. :)
Loading...
In case you want to validate data which stored on server, good practice do it on server-side. If validation on server will be unsuccessful, server should send not 200 HTTP code, therefore save metod of Backbone.Model will trigger error.
Other side, for validation data backbone has unimplemented validate method. I guess that right choise to implement and use it. But keep in mind that validate is called before set and save, and if validate returns an error, set and save will not continue, and the model attributes will not be modified. Failed validations trigger an "error" event.
Another way, when we call silent set(with {silent: true} param), we should call isValid method manually to validate data.
Too many things render themselves too much..
You have to separate your Views under their logic. Good practice for collection is separate view for each model. In this case you could render each element independently. And even more - when you initalizing your container view for collection, you could bind any event from each model in the collection to appropriate view, and they will render automatically.
Great, but the H2 at the start of the form is the same name as in the
input - you need to update it. Oh, and you need to update the name on
the list to the side.
you could use JQuery on method to implement callback which send value to display. Example:
//Container view
init: function() {
this.collection = new Backbone.Collection({
url: 'http://mybestpage.com/collection'
});
this.collection.bind('change', this.render, this);
this.collection.fetch();
},
render: function() {
_.each(this.collection.models, function(model) {
var newView = new myItemView({
model: model,
name: 'view' + model.id
});
this.$('#my-collection').append(newView.render().$el);
view.on('viewEdit', this.displayValue);
}, this);
},
...
displayValue: function(value) {
//method 1
this.displayView.setText(value); //we can create little inner view before,
//for text displaying. Сonvenient at times.
this.displayView.render();
//method 2
$(this.el).find('#display').html(value);
}
//View from collection
myItemView = Backbone.View.extend({
events: {
'click #edit': 'edit'
},
init: function(options) {
this.name = options.name;
},
...
edit: function() {
this.trigger('viewEdit', this.name, this);
}
OH, and the list sorts itself by names!
You can use sort method for backbone collections. But (!) Calling sort triggers the collection's "reset" event. Pass {silent: true} to avoid this. How to
Here's another example: You want to create a new item in the
collection...
When we press a "New" button we need to create a new model, but only when .save() method will trigger success, we should push this model to collection. In another case we should display error message. Of course we have no reasons to add a new model to our collection until it has been validated and saved on server.
It's subviews all the way down... subviews become zombie-like or do not respond.
when you (or any model) calling render method, all elements inside it will be recreated. So in case when you have subviews, you should call subView.delegateEvents(subView.events); for all of subviews; Probably this method is little trick, but it works.
Flickering..
Using thumbnails for big and medium images will minimize flickering in lot of cases. Other way, you could separate rendering of view to images and other content.
Example:
var smartView = Backbone.View.extend({
initialize: function(){
this.model.on( "imageUpdate", this.imageUpdate, this );
this.model.on( "contentUpdate", this.contentUpdate, this );
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
},
imageUpdate: function(){
this.$el.find('#image').attr('src', this.model.get('imageUrl'));
},
contentUpdate: function(){
this.$el.find('#content').html(this.model.get('content'));
}
})
I hope this helps anyone. Sorry for grammar mistakes, if any :)
Loading...
I'm a huge fan of eager loading. All my server calls are JSON responses, so it isn't a huge deal to make them more often than not. I usually refresh a collection every time it's needed by a view.
My favorite way to eager load is by using Backbone-relational. If I organize my app in a hierarchical manner. Consider this:
Organization model
|--> Event model
|--> News model
|--> Comment model
So when a user is viewing an organization I can eager load that organization's events and news. And when a user is viewing a news article, I eager load that article's comments.
Backbone-relational provides a great interface for querying related records from the server.
Too many things render themselves too much...
Backbone-relational helps here too! Backbone-relational provides a global record store that proves to be very useful. This way, you can pass around IDs and retrieve the same model elsewhere. If you update it in one place, its available in another.
a_model_instance = Model.findOrCreate({id: 1})
Another tool here is Backbone.ModelBinder. Backbone.ModelBinder lets you build your templates and forget about attaching to view changes. So in your example of collecting information and showing it in the header, just tell Backbone.ModelBinder to watch BOTH of those elements, and on input change, your model will be updated and on model change you view will be updated, so now the header will be updated.
It's subviews all the way down... subviews become zombie-like or do not respond...
I really like Backbone.Marionette. It handles a lot of the cleanup for you and adds an onShow callback that can be useful when temporarily removing views from the DOM.
This also helps to facilitate attaching jQuery plugins. The onShow method is called after the view is rendered and added to the DOM so that jQuery plugin code can function properly.
It also provides some cool view templates like CollectionView that does a great job of managing a collection and its subviews.
Flickering
Unfortunately I don't have much experience with this, but you could try pre-loading the images as well. Render them in a hidden view and then bring them forward.

Does backbonejs use "live binding" like canjs?

I've been comparing js mvc's and noticed that a nice amount of people are bragging on the "live binding" that canjs does. Can someone explain what exactly it is and how it helps in comparison to the other popular mvc's like backbonejs, spine, etc...
You use live binding because with CanJS, you replace all that code with:
<h1><%= model.attr('name') %></h1>
Backbone does support implementing model binding, but it's not automatic as in some other client-side application frameworks, for example, AngularJS's data-binding through ng-controller or EmberJS's bindAttr.
For some really rudimentary code to update views as a model's state changes, use Backbone.View's events object, as in this example:
var ExampleView = Backbone.View.extend({
id: 'myView',
events: {
// using an #id selector here is also acceptable
'change [data-attrname=name]': function(e) {
// update the value in the model
this.model.set('name', $(e.target).val());
}
},
initialize: function(options) {
this.model.on('change', this.render, this);
},
render: function() {
var html = _.template('<h1 data-attrname="name"><%= name %></h1>',
this.model.toJSON());
this.$el.html(html);
return this;
}
});
Which will render the following HTML (myView is the div implicitly created by ExampleView):
<div id="myView">
<h1 data-attrname="name"></h1>
</div>
This is essentially doing binding manually from the UI and wholesale (re-rendering the entire view) when the model changes. Backbone is intentionally designed to be less opinionated than some other frameworks, to allow you to implement things as you see fit with the addition of other libraries.
For some more sophisticated techniques on how to model bind more automatically, here are a few resources listed by their authors:
Los Techies / Derek Bailey
theironcook
XTargets

Categories

Resources