I am working on my first project using backbone.js. It should be a frontend to a Play! App with a JSON interface. Here's a part of my JS code
var api = 'http://localhost:9001/api'
// Models
var Node = Backbone.Model.extend();
// Collections
var Nodes = Backbone.Collection.extend({
model: Nodes,
url: api + '/nodes',
});
// Views NODE
var NodeView = Backbone.View.extend({
el: $("#son_node_elements"),
render: function(){
var source = $("#son_node_item_templ").html();
var template = Handlebars.compile(source);
$(this.el).append(template(this.model.toJSON()));
return this;
}
});
var NodeListView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, "render");
this.collection = new Nodes();
this.collection.bind("change",this.render);
this.collection.fetch();
this.render();
},
render: function(){
_(this.collection.models).each(function(item){
var nodeView = new NodeView({model: item});
$(this.el).append(nodeView.render().el);
}, this);
}
});
Nodes = new NodeListView({el:$('#son_nodes')});
My Problem is that when this.render() is called, this.collection.fetch() is still not done and this.collection does not contain anithing to render. All works fine when I set a breakpoint at this.render() (for example using firebug), so this.render() is not called immediately. I get exactly the same result when I access a local JSON file instead of the api of my app. Any suggestions how to handle this issue?
Fetch can also be called from outside view, so let the view listen for that instead:
this.collection.bind("reset",this.render);
Reset event will be triggered on every call to this.collection.fetch();
And finally, skip this.render(); Don't call this yourself, since reset event handler do this for you.
You need to call "render" inside the "success" callback for your "fetch()":
this.collection.fetch({
success: function(col) {
col.render();
}
});
That defers the rendering until the collection fetching is complete. It's all asynchronous.
Caveat: I barely know anything about Backbone in particular, but something along these lines is definitely your problem. In other words, there may be other things to worry about that I haven't mentioned (because I don't know what they are :-).
Related
My Chrome Extension has two main components scripts:
popup.js and popup.html - the extension logic and UI respectively.
scrape.js - JavaScript embedded into a webpage to scrape a key value.
scrape.js - is very simple. It does only two things:
Scrape webpage for key.
Run 6 distinct database queries using scraped key.
Because of the library involved (outside of my control) the database queries must be run from scrape.js (i.e. in the context of tab's web page).
When (or more importantly, if) each of 6 queries completes, scrape.js calls popup.js notifying it some data is ready for rendering.
Upon receiving the callback notification popup.js uses Backbone models and views to render the data provided by scrape.js:
var modelA = Backbone.Model.extend({...});
modelA.set({...});
var modelB = Backbone.Model.extend({...});
modelB.set({...});
These models are created from callbacks and only exist if the relevant callback is made by scrape.js to popup.js. In this sense the models and any views that render them are optional.
If a callback is made, a model is stored in a global variable modeInstances so I may render it later. If all 6 queries complete, 6 callbacks are made and 6 Backbone model instances will be stored in modeInstances.
When popup.js receives a final callback, it renders any models and views:
modelInstances.a = modelA; // Could be undefined.
modelInstances.b = modelB; // Could be undefined.
I have three Backbone.js views, one of these views renders both models (A and B):
var viewA = new Views.ViewA({
modelA: modelInstances.modelA,
});
viewA.render();
var viewB = new Views.ViewB({
modelB: modelInstances.modelB,
});
viewB.render();
var viewAandB = new Views.ViewAandB({
modelA: modelInstances.modelA,
modelB: modelInstances.modelB,
});
viewAandB.render();
If either modelA or modelB were not created, I receive an exception in the View's initialize method (read code comments below):
Views.ViewAandB = Backbone.View.extend({
initialize: function(options) {
var self = this;
// Even if models are undefined, this is OK.
this.modelA = options.modelA;
this.modelB = options.modelB;
_.bindAll(this, 'render');
// This fails if models are undefined.
this.bidderModel.bind('change', this.render);
this.buyerModel.bind('change', this.render);
},
});
I could surround the the code which creates the view with a condition, but this feels messy:
if (modelInstances.modelA && modelInstances.modelB) {
var viewAandB = new Views.ViewAandB({
modelA: modelInstances.modelA,
modelB: modelInstances.modelB,
});
viewAandB.render();
}
I could check inside the view's initialize and render methods, but this too feels messy since it must be duplicated in any method using the view's model:
initialize: function(options) {
var self = this;
var haveModels = (options.modelA && options.modelB);
if(!haveModels) {
// No data.
return;
}
// Even if models are undefined, this is OK.
this.modelA = options.modelA;
this.modelB = options.modelB;
_.bindAll(this, 'render');
// This fails if models are undefined.
this.bidderModel.bind('change', this.render);
this.buyerModel.bind('change', this.render);
},
Question: How should I check the necessary models are created when rendering 'optional' views?
I'm using Backbone and I have the following model and collection
App.Models.Person = Backbone.Model.extend({
});
App.Collections.People = Backbone.Collection.extend({
model: App.Models.Person,
url: 'api/people',
});
However what I'm struggling on is the best way to render this collection. Here's how I've done it so far which works but doesn't seem to be the most elegant solution
App.Views.PeopleView = Backbone.View.extend({
el: $(".people"),
initialize: function () {
this.collection = new App.Collections.People();
//This seems like a bad way to do it?
var that = this;
this.collection.fetch({success: function(){
that.render();
}});
},
render: function () {
var that = this;
_.each(this.collection.models, function (item) {
that.renderPerson(item);
}, this);
},
I'm fairly new to Backbone but have to assign this to a different variable to I use it inside of the success function just seems like a bad way of doing things? Any help on best practices would be appreciated.
Backbone allows you to register for events that you can react to. When the collection is synchronized with the server, it will always fire the sync event. You can choose to listen for that event and call any given method. For instance ...
initialize: function () {
this.collection = new App.Collections.People();
this.listenTo(this.collection, "sync", this.render);
// Fetch the initial state of the collection
this.collection.fetch();
}
... will set up your collection so that it would always call this.render() whenever sync occurs.
The docs on Backbone Events are succinct but pretty good. Keep in mind a few things:
The method you use to register event listeners (i.e. listenTo or on) changes how you provide the context of the called function. listenTo, for instance, will use the current context automatically; on will not. This piece of the docs explains it pretty well.
If you need to remove a view, you will need to disconnect event listeners. The easiest way to do that is to use listenTo to connect them in the first place; then when destroying the view you can just call view.stopListening().
For rendering, there are a lots of suggestions for how to do it. Generally having a view to render each individual model is one way. You can also use Backbone.Collection#each to iterate over the models and control the scope of the iterating function. For instance:
render: function() {
this.collection.each(function(model) {
var view = new App.Collections.PersonView({ model: model });
view.render();
this.$el.append(view.$el);
}, this);
}
Note the second argument to .each specifies the scope of the iterator. (Again, have a look at the docs on controlling scope. If you'd rather have a framework help out with the rendering, check out Marionette's CollectionView and ItemView.
If your view is supposed to just render the collection you can send the collection to temnplate and iterate through in template, otherwise you can create another subView for that purpose or send the individual models of the collection to another subview and append to the container, hope it was helpful.
I have a model which can be edited by a certain view; however, at the bottom of the view the user should get an option to save or discard all changes. This means that you will need to store a list of all the changes to be made to the model and then make those changes only once the 'save' button has been clicked. This sounds unnecessarily complicated and I have come up with an idea of an alternative approach which is to create a clone of the model and make changes to that in the view. Then if the user clicks 'save' delete the old model and replace it in its collection with the new one, otherwise you discard the cloned model.
This this an acceptable approach, and if so, how can I implement the cloning process?
This would be equivalent to fetching the data from the server again (but an extra HTTP request seems unnecessary).
You could use the clone method. Short example below:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
this.realModel = this.model;
this.model = this.realModel.clone();
},
onSave: function() {
this.realModel.set(this.model.attributes);
}
});
You could also do something a bit different:
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
initialize: function() {
// save the attributes up front, removing references
this._modelAttributes = _.extend({}, this.model.attributes);
},
onSave: function() {
// revert to initial state.
this.model.set(this._modelAttributes);
}
});
You can give Backbone.Memento a try.
If you don't want to use it no problem. But, You can get a good idea about how it should be done from the codebase.
I usually solve this issue with an object cache on the view. That way I don't add any unnecessary overhead to model/view management. Discarding happens naturally if the user closes out of a view without saving.
var Model = Backbone.Model.extend({
'title': 'Hello'
});
var View = Backbone.View.extend({
initialize: function() {
// Holds temporary values until save
this.cache = {};
},
onTitle: function() {
this.cache.title = 'World';
},
onSave: function() {
this.model.set( this.cache );
}
});
I have my views correctly displaying fake information and so I am now trying to apply asynchronus data loading to retrieve actual data. The problem is that I am uncertain about how I should go about this. Should I create AJAX calls myself? Should I use the Socket API? Should I use the built in REST api (and how to do so asynchronously)? The server side handler is still unimplemented so as far as how the server serves up the data, that is completely flexible.
i doubt your own ajax calls is what is needed here...
i can't tell about sockets however i know it is possible and a solid idea depending on your app.
i have been using the default REST functionality and it works well for me,
a small example as how I would do it,
to make it less complex i will just act as if it is from page load, instead of using routers and all.
var myView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
var v = this;
this.model.bind("change", function(e) {
this.render();
});
},
render: function() {
this.el.empty();
this.el.text(this.model.get('name'));
}
});
var myModel = Backbone.Model.extend({
url: "/api/myModel", // change to your server code...
defaults: {
name: "john"
}
});
$(function(){
var m = new myModel({}); // dummy model
var v = new myView({ model: m, el: $('#myDiv')});
v.render();
m.fetch(); // takes the url of the model or collection and fetches it from the server side ...
});
if you want to test what the fetch would do, you can for try this code from your console, (or add it to the jquery document load function:
m.set({ name: 'peter' });
this changes the model's property 'name' and you will immediately see the view update itself, because it listens to the change event of the model.
more info on these events can be found here: http://documentcloud.github.com/backbone/#Events
Is there any sort of hooks in backbone where I can easily say "whenever any of the collections is fetching data, show the spinner, hide it when they're done"?
I have a feeling it will be more complicated than that and require overwriting specific functions. When should I show the spinner? On fetch() or refresh() or something else?
You can use jQuery ajaxStart and ajaxStop. Those will globally run when an ajax request is made, so fetch and save will cause those to run. Add your code to show the spinner in the start and hide it in the end.
in Backbone.js 1.0.0 you can use the request and sync events http://backbonejs.org/#Events-catalog
This goes in the view.
initialize: function(){
this.items = new APP.Collections.itemCollection();
this.items.bind('request', this.ajaxStart, this);
this.items.bind('sync', this.ajaxComplete, this);
}
ajaxStart: function(arg1,arg2,arg3){
//start spinner
$('#item-loading').fadeIn({duration:100});
},
ajaxComplete: function(){
$('#item-loading').fadeOut({duration:100});
}
This can be applied per collection or per model here's some CSS for the spinner http://abandon.ie/notebook/simple-loading-spinner-for-backbonejs
Backbone doesn't trigger any event when Collection::fetch() starts (see source code), so you will have to override the fetch method. Maybe something like this:
var oldCollectionFetch = Backbone.Collection.prototype.fetch;
Backbone.Collection.prototype.fetch = function(options) {
this.trigger("fetch:started");
oldCollectionFetch.call(this, options);
}
This will override the fetch method to give you an event when the fetch starts. However, this only triggers the event on the specific collection instance so if you have a bunch of different collections you'll have to listen for that event on each collection.
The way i have done this without overriding backbone is:
In view
var myView = Backbone.View.extend({
initialize; function(){
this.$el.addClass('loading');
collection.fetch(success:function(){
this.$el.removeClass('loading')
})
}
})
The other route would be to remove the loading class when the models are added, usually you have:
var myView = Backbone.View.extend({
initialize; function(){
_.bindAll(this, 'addAll')
collection.bind('reset', this.addAll)
this.$el.addClass('loading');
collection.fetch();
},
addAll: function(){
this.$el.removeClass('loading');
collection.each(this.addOne);
}
})
These would be almost identical in most cases, and as the loader is really for the users experience removing it just prior to displaying the content makes sense.
And a little update. Since Dec. 13, 2012 have been added a "request" event to Backbone.sync, which triggers whenever a request begins to be made to the server. As well since Jan. 30, 2012 have been added a "sync" event, which triggers whenever a model's state has been successfully synced with the server (create, save, destroy).
So, you don't need to override or extand the native Backbone's methodes. For listening 'start/finish fetching' event you can add listener to your model/collection like this for example:
var view = new Backbone.View.extend({
initialize: function() {
this.listenTo(this.model, 'request', this.yourCallback); //start fetching
this.listenTo(this.model, 'sync', this.yourCallback); //finish fetching
}
});
You can create a method called sync on any of your models, and backbone.js will call that in order to sync. Or you can simply replace the method Backbone.sync. This will allow you to make the change in only one place in your source code.
I have used NProgress in my backbone and it is the best functioning loader/spinner out there.
var view = Backbone.View.extend({
initialize: function () {
this.items = new APP.Collections.itemCollection();
this.items.on('reset', this.myAddFunction, this);
NProgress.start();
collection.fetch({
reset:true,
success: function () {
NProgress.done(true);
}
});
}
});
Use Backbone sync method,
It will call every time backbone sync method, not only fetch, save, update and delete also
/* over riding of sync application every request come hear except direct ajax */
Backbone._sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
// Clone the all options
var params = _.clone(options);
params.success = function(model) {
// Write code to hide the loading symbol
//$("#loading").hide();
if (options.success)
options.success(model);
};
params.failure = function(model) {
// Write code to hide the loading symbol
//$("#loading").hide();
if (options.failure)
options.failure(model);
};
params.error = function(xhr, errText) {
// Write code to hide the loading symbol
//$("#loading").hide();
if (options.error)
options.error(xhr, errText);
};
// Write code to show the loading symbol
//$("#loading").show();
Backbone._sync(method, model, params);
};