I'm struggling with a design decision and looking for some feedback. I don't think this question is necessarily specific to Backbone, but that's the framework I'm currently using.
I'm wondering if it's considered bad practice to store the classname of a view as part of a model. For example, let's say you have a parent view with multiple subviews of different types. Each subview contains an edit link, and when that edit link is clicked, the parent view should update it's contents to contain the edit view for that model. I'm using an "event bus" to orchestrate events.
For example:
var E = _.extend({}, Backbone.Events);
var ParentView = Backbone.View.extend({
initialize: function(options) {
this.apples = options.apples; // Backbone Collection of Apple models
this.oranges = options.oranges; // Backbone Collection of Orange models
this.$appleList = this.$('#apples');
this.$orangeList = this.$('#oranges');
this.$editScreen = this.$('#edit-screen');
// listen to edit events for models and render the
// edit screen for using the appropriate view
this.listenTo(E, 'edit', this.showEditScreen);
},
template: 'templates/parent',
render: function() {
this.$el.html(this.model.toJSON());
this.renderAppleViews();
this.renderOrangeViews();
},
renderAppleViews: function() {
var view = new AppleListView({collection: this.apples});
this.$appleList.html(view.render().el);
},
renderOrangeViews: function() {
var view = new OrangeListView({collection: this.oranges});
this.$orangeList.html(view.render().el);
},
// Show the edit screen for a particular model
showEditScreen: function(model) {
var view = new window[model.editScreenViewClass]({model: model}):
this.$editScreen.html(view.render().el);
}
});
AppleListView and OrangeListView simply loop through their respective collections and append a view to the list.
AppleListView adds AppleItemViews, and OrangeListView adds OrangeItemViews. I'm showing the relevant parts of those views below:
var AppleItemView = Backbone.View.extend({
events: {
'click .edit': 'onEditClick'
},
onEditClick: function(e) {
e.preventDefault();
E.trigger('edit', this.model);
}
});
var OrangeItemView = Backbone.View.extend({
events: {
'click .edit': 'onEditClick'
},
onEditClick: function(e) {
e.preventDefault();
E.trigger('edit', this.model);
}
});
Here is what the models would look like for this to work:
var Apple = Backbone.Model.extend({
editScreenViewClass: 'AppleEditView'
});
var Orange = Backbone.Model.extend({
editScreenViewClass: 'OrangeEditView'
});
I'm asking if it seems "ok" to store this editScreenViewClass on the model. That way I can retrieve it directly from the model passed into the event.
Related
I am trying to understand backbone and am currently struggling with zombie views. I have read many stack overflow posts on the matter but I still cannot figure it out.
For the sake of simplicity, I set up two views (without data) that I need to switch.
What I did so far was:
creating an object
//define application object
var app = {
vent: {},
templates: {},
views: {},
routers: {},
};
//instantiate event aggregator and attach it to app
app.vent = _.extend({}, Backbone.Events);
defining two very simple templates (stored into app.templates): the first one has some dummy text and a button (with and id of 'test-begin'), the second one just dummy text
defining two views
app.views.instructions = Backbone.View.extend({
//load underscore template
template: _.template(app.templates.instructions),
//automatically called upon instantiation
initialize: function(options) {
//bind relevant fucntions to the view
_.bindAll(this, 'render', 'testBegin', 'stillAlive', 'beforeClose');
//listen to app.vent event
this.listenTo(app.vent, 'still:alive', this.stillAlive);
},
//bind events to DOM elements
events: {
'click #test-begin' : 'testBegin',
},
//render view
render: function() {
this.$el.html(this.template());
return this;
},
//begin test
testBegin: function() {
Backbone.history.navigate('begin', {trigger: true});
},
//still alive
stillAlive: function() {
console.log('I am still alive');
},
//before closing
beforeClose: function() {
//stop listening to app.vent
this.stopListening(app.vent);
},
});
//test view
app.views.test = Backbone.View.extend({
//load underscore template
template: _.template(app.templates.test),
//automatically called upon instantiation
initialize: function(options) {
//trigger still:alive and see if removed view responds to it
app.vent.trigger('still:alive');
//bind relevant fucntions to the view
_.bindAll(this, 'render');
},
//render view
render: function() {
this.$el.html(this.template());
return this;
},
});
defining a router
//base router
app.routers.baseRouter = Backbone.Router.extend({
//routes
routes: {
'': "instructions",
'begin': "beginTest"
},
//functions (belong to object controller)
instructions: function() {baseController.instructions()},
beginTest : function() {baseController.beginTest()},
});
//baseRouter controller
var baseController = {
instructions: function() {
mainApp.viewsManager.rederView(new app.views.instructions());
},
beginTest: function(options) {
mainApp.viewsManager.rederView(new app.views.test());
},
};
defining mainApp (with a view-switcher)
//define mainApplication object
mainApp = {};
//manages views switching
mainApp.viewsManager = {
//rootEl
rootEl: '#test-container',
//close current view and show next one
rederView : function(view, rootEl) {
//if DOM el isn't passed, set it to the default RootEl
rootEl = rootEl || this.rootEl;
//close current view
if (this.currentView) this.currentView.close();
//store reference to next view
this.currentView = view;
//render next view
$(rootEl).html(this.currentView.render().el);
},
};
//render first view of app
mainApp.viewsManager.rederView(new app.views.instructions());
//initiate router and attach it to app
mainApp.baseRouter = new app.routers.baseRouter();
//start Backbone history
Backbone.history.start({silent: true
});
adding a close function to view via Backbone prototype
//add function to Backbone view prototype (available in all views)
Backbone.View.prototype.close = function () {
//call view beforeClose function if it is defined in the view
if (this.beforeClose) this.beforeClose();
//this.el is removed from the DOM & DOM element's events are cleaned up
this.remove();
//unbind any model and collection events that the view is bound to
this.stopListening();
//check whether view has subviews
if (this.hasOwnProperty('_subViews')) {
//loop thorugh current view's subviews
_(this._subViews).each(function(child){
//invoke subview's close method
child.close();
});
}
};
So, in order to check for zombie views, the second view triggers and event (still:alive) that the first view listen to and respond to it via a message sent to the console.log (although it really shouldn't).
The first view does listen to such a message (in the console log I read 'I am still alive) even when it has been replaced by the second view.
Can you help me? thank you very.
Long post, if you have any questions, please ask
A Zombie View is just a view that is not in the DOM, but listens to and reacts to events -- sometimes this behavior is expected, but not typically.
If the DOM Event handlers for the view are not properly removed, the view and it's in-memory HTML fragments will not be garbage collected. If the Backbone.Event handlers are not unbound properly, you could have all sorts of bad behavior... such as a bunch of "Zombie" view triggering AJAX requests on models. This problem was very common on older versions of Backbone prior to stopListening and listenTo especially if you shared models between views.
In your code, you don't have a Zombie View, because you are properly closing your views.
You can see the console.log because you are initializing the second view (and triggering the event still:alive) before you close the first view.
To switch views, you are calling:
mainApp.viewsManager.rederView(new app.views.test());
Calling new app.views.test() initializes the second view which triggers the event that the first listens to.
If you update your code to the following, you won't see the console.log anymore.
//baseRouter controller
var baseController = {
instructions: function() {
mainApp.viewsManager.rederView(app.views.instructions);
},
beginTest: function(options) {
mainApp.viewsManager.rederView(app.views.test);
},
};
And update rederView
rederView : function(ViewClass, rootEl) {
//if DOM el isn't passed, set it to the default RootEl
rootEl = rootEl || this.rootEl;
//close current view
if (this.currentView) this.currentView.close();
//store reference to next view
this.currentView = new ViewClass();
//render next view
$(rootEl).html(this.currentView.render().el);
},
If you remove this line from your close method, you will have a zombie view and should see the console.log.
//unbind any model and collection events that the view is bound to
this.stopListening();
Zombie View Example
In the following code, I am creating 100 views, but only displaying 1 in the DOM. Every view contains the same model and listens to it's change event. When the view's <button> element is clicked, it updates the model which causes every view's model change handler to be executed, calling fetch 100 times... 100 AJAX requests!
The view's change handlers are called 100 times, because the view close method does not call this.stopListening(), so even when the views are removed from the page, they all still listen to the model's events. Once you click the button, the model is changed, and all of the zombie views respond, even though they're not on the page.
var TestView = Backbone.View.extend({
tagName: 'h1',
initialize: function(options) {
this.i = options.i;
this.listenTo(options.model, 'change', function(model) {
model.fetch();
});
},
events: {
'click button': function() {
this.model.set("show_zombies", Date.now());
}
},
render: function() {
this.$el.append("<button>Click To Test for Zombies!</button>");
return this;
},
close: function() {
this.$el.empty(); // empty view html
// this.$el.off(); // // Whoops! Forgot to unbind Event listeners! (this view won't get garbage collected)
// this.stopListening() // Whoops! Forgot to unbind Backbone.Event listeners.
}
});
var model = new (Backbone.Model.extend({
fetch: function() {
document.body.innerHTML += "MODEL.FETCH CALLED<br />"
}
}));
var v;
for (var i = 1; i < 101; i++) {
if (v) v.close();
v = new TestView({
'i': i,
'model': model
}).render();
$('body').html(v.el);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone.js"></script>
I'm working with an API and Backbone.js at the moment.
I have two views, both render to the same document element #viewContainer. Both of these views render a table with a couple strings to decribe them and a button that opens a form in a modal.
View 1
App.Views.TaskList = Backbone.View.extend({
el: "#viewContainer",
tagName: 'tr',
events: {
"click button": "showTaskForm"
},
showTaskForm: function (event) {
event.preventDefault();
var id = $(event.currentTarget).data("id");
var item = this.collection.get(id);
var formView = new App.Views.Form({
model: item
});
formView.render();
},
render: function () {
changeActive($('#tasksLink'));
var template = _.template($("#taskList").html(), {});
$('#viewContainer').html(template);
// loop and render individual tasks.
this.collection.each(function (model) {
var variables = {
name: model.get('name'),
button: model.getButton()
};
var template = _.template($("#task").html(), variables);
$("#taskTable tbody").append(template);
});
},
collection: App.Collections.Tasks,
});
View 2
App.Views.ProcessList = Backbone.View.extend({
el: "#viewContainer",
tagName: 'tr',
events: {
"click button": "showStartForm"
},
showStartForm: function (event) {
event.preventDefault();
var id = $(event.currentTarget).data("id");
var item = this.collection.get(id);
var formView = new App.Views.Form({
model: item
});
formView.render();
},
collection: App.Collections.Processes,
render: function () {
changeActive($('#processLink'));
var template = _.template($("#processList").html(), {});
$('#viewContainer').html(template);
this.collection.each(function (model) {
var variables = {
processId: model.get('id'),
processName: model.get('name'),
button: model.getButton()
};
var template = _.template($('#process').html(), variables);
$('#processList tbody').append(template);
});
} });
Neither of these views are rendered by default, both need to be activated by a button on the page and they over-write each other in the DOM. However, which ever view is rendered first, the click event of the buttons in that view are the ones that are always fired.
If there is any more information needed from me let me know and I will edit the question.
Be sure to call undelegateEvents() in the first view when you render the second.
Since you're listening for events on the same elements, essentially you attached two listeners for click events on the same button, and when you change your views you are not cleaning up these listeners.
Here's an article that talks about managing events on view change, which should be really helpful to you.
http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/
As other posters have pointed out, you need to watch out for 'zombie' views (i.e. making sure you undelegate events). If you're building even a moderately complex app, you'll want something that can scale. I find this pattern useful:
var BaseView = Backbone.View.extend({
render: function () {
this.$el.html(this.template());
return this;
},
close: function () {
if (this.onClose) this.onClose();
this.undelegateEvents();
this.$el.off();
this.$el.remove();
}
});
Then whenever you build a view you can do:
var view = BaseView.extend({
//your code
//now the .close() method is available whenever you need to close
//a view (no more zombies!).
});
I'm creating a Backbone app with a section to view reports; the section has three parts: a menu of report links, the title of the displayed report, and the content of the displayed report. The user is to click on a report link, which will fetch the associated model's data. Then the report title and content should update accordingly. However, I'm not sure how the view bindings should work, and each report may return slightly different data that requires a different view template. Here's my JSFiddle (fetch method overridden just for this example)
Right now, I have a Backbone model for each report and a Backbone collection of all the reports:
App.Models.Report = Backbone.Model.extend();
App.Collections.Reports = Backbone.Collection.extend({
model: App.Models.Report,
url: "/reports"
});
The menu view is tied to the collection and on click, sets App.State.title and App.State.cid, which the other two views are listening to:
App.Views.ReportLink = Backbone.View.extend({
tagName: 'li',
className: 'is-clickable',
initialize: function() {
this.render();
},
render: function() {
this.el.innerHTML = this.model.get('title');
this.$el.attr('data-CID', this.model.cid); // store the model's cid
}
});
App.Views.ReportMenu = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.listenTo(this.collection, 'reset', this.render)
this.render();
this.$el.on('click', 'li', function() {
App.State.set({
'title': this.innerHTML,
'cid': $(this).attr('data-CID') // cid of the clicked view's model
});
});
},
The difficulty is with the report content; what it currently does is listen for changes to App.State.cid and then calls fetch on the given model with that cid. This fetch populates the model with a sub-collection of report rows. The report content view then set its html based on the sub-collection data, and it is also supposed to apply the correct template to the data:
App.Views.ReportContent = Backbone.View.extend({
initialize: function(attrs) {
this.listenTo(this.model, 'change:cid', this.render);
this.reportsCollection = attrs.reportsCollection;
},
render: function() {
var self = this,
cid = this.model.get('cid'),
model = this.reportsCollection.get(cid);
model.fetch({
success: function() {
var html = '';
model.subCollection.each(function(model) {
var template = _.template($('#templateReportA').html()); // want to dynamically set this
html += template(model.toJSON());
});
self.$el.html(html);
}
});
}
});
1) Is this the correct sort of implementation for this type of multiple view situation with a collection?
2) How can I pass the correct template that needs to apply for each individual report? Right now I'm explicitly passing the view template for report A. I can think of storing it on the model but the template should be associated with the view.
If your cids are all made up of characters that are legal in HTML ids, then a simple solution would be to name all your report templates templateReportxxx where "xxx" is the report's cid and then just change the template-loading line to
var template = _.template($('#templateReport'+cid).html());
I have a series of comments on a page, which can be edited. My idea was to render the comments by Rails and preload a json with all those comments in a Backbone Collection.
Then I would poll every x seconds, to see if there are changes. Normally I render the collection by looping over all the models, and create a view for each item. When a model gets updated, so will the view (comment im this case).
But my question is this, how do you bind a view to the model, when the view is already in the DOM. Especially since the view had a dynamic id. There is no point in rendering the view, since it's already there. When you render a view, backbone binds it through somekind of cid.
The only solution I can think of, is by setting an id in the dom object on pageload. iow
<div id="comment-<%= content.id %>"></div>
. And then in the initialize of the view, reset the id
class Comment extends Backbone.View
initialize: ->
#id = "comment-" + #model.get('id')
But I'm not sure if thats the way to go. Would events still be binded?
Special for you :)
var CommentsView = Backbone.View.extend({
tagName : 'ul',
comments : {},
initialize : function () {
this.listenTo(this.collection, 'add', this.addComment);
this.listenTo(this.collection, 'remove', this.removeComment);
this.listenTo(this.collection, 'change', this.updateComment);
},
addComment : function (model) {
this.comments[model.id] = new CommentView({model:model});
this.$el.append(this.comments[model.id].render().$el);
},
removeComment : function (model) {
this.comments[model.id].remove();
this.comments[model.id] = null;
},
updateComment : function (model) {
this.comments[model.id] = new CommentView({model:model});
this.$('[data-id="' + model.id + '"]').before(this.comments[model.id].render().$el).remove();
}
});
var CommentView = Backbone.View.extend({
tagName : 'li',
template : _.template('<div data-id="<%= id %>"><%= name %>: <%- message %></div>'),
render : function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
// comments
var initialComments = [{id:1, name:'user1', message:'great!'}, {id:2, name:'user2', message:':)'}];
var actualComments = [{id:1, name:'user1', message:'great! [edited]'}];
var comments = new Backbone.Collection();
var commentsView = new CommentsView({collection:comments});
// show comments
commentsView.render().$el.appendTo('body');
// simulate fetch
comments.add(initialComments);
// simulate update
_.delay(function() {
comments.update(actualComments);
},
2000);
jsfiddle
Here is my content.js in which i am using backbone.js for rendering contents.
// Our basic **Content** model has `content`, `order`, and `done` attributes.
var Content = Backbone.Model.extend({
// If you don't provide a Content, one will be provided for you.
EMPTY: "empty Content...",
// Ensure that each Content created has `content`.
initialize: function() {
}
});
var ContentCollection = Backbone.Collection.extend({
model : Content
});
// Create our global collection of **Todos**.
window.Contents = new ContentCollection;
// The DOM element for a Content item...
var ContentView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
events: {
"click .content": "open"
},
// a one-to-one correspondence between a **Content** and a **ContentView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
_.bindAll(this, 'render', 'close');
this.model.bind('change', this.render);
this.model.view = this;
},
// Re-render the contents of the Content item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
Here is how i am making the list of content and rendering them.
for(var i=0; i<data.length; i++) {
var content = new Content(data[i]);
var templ=_.template($('#tmpl_content').html());
var view = new ContentView({model: content});
view.template=templ;
$("#content").append(view.render().el);
}
my question is how can i get the contetnt model listing .
as i have created the collection
var ContentCollection = Backbone.Collection.extend({
model : Content
});
// Create our global collection of **Todos**.
window.Contents = new ContentCollection;
So when i do watch Contents it shows length 0 and models [] .
how contetnt will get added in the collection . or how to see list of model in backbone.js
You need to Collection.add(models) before it will contain anything.
You also could specify a URL (which should return a JSON array of models) on your collection and then do window.Contents.fetch(). Backbone will auto-populate the model (Content) specified in your collection and automatically add them to your collection.