I'm having some trouble getting change events to fire when a model is updated via polling of an endpoint. I'm pretty sure this is because the collection is not actually updated. I'm using the new option (update: true) in Backbone 0.9.9 that tries to intelligently update a collection rather than resetting it completely.
When I insert a console.log(this) at the end of the updateClientCollection function, it appears that this.clientCollection is not updating when updateClientCollection is called via setInterval. However, I do see that the endpoint is being polled and the endpoint is returning new and different values for clients.
managementApp.ClientListView = Backbone.View.extend({
className: 'management-client-list',
template: _.template( $('#client-list-template').text() ),
initialize: function() {
_.bindAll( this );
this.jobId = this.options.jobId
//the view owns the client collection because there are many client lists on a page
this.clientCollection = new GH.Models.ClientStatusCollection();
this.clientCollection.on( 'reset', this.addAllClients );
//using the initial reset event to trigger this view's rendering
this.clientCollection.fetch({
data: {'job': this.jobId}
});
//start polling client status endpoint every 60s
this.intervalId = setInterval( this.updateClientCollection.bind(this), 60000 );
},
updateClientCollection: function() {
//don't want to fire a reset as we don't need new view, just to rerender
//with updated info
this.clientCollection.fetch({
data: {'job': this.jobId},
update: true,
reset: false
});
},
render: function() {
this.$el.html( this.template() );
return this;
},
addOneClient: function( client ) {
var view = new managementApp.ClientView({model: client});
this.$el.find( 'ul.client-list' ).append( view.render().el );
},
addAllClients: function() {
if (this.clientCollection.length === 0) {
this.$el.find( 'ul.client-list' ).append( 'No clients registered' );
return;
}
this.$el.find( 'ul.client-list' ).empty();
this.clientCollection.each( this.addOneClient, this );
}
});
managementApp.ClientView = Backbone.View.extend({
tagName: 'li',
className: 'management-client-item',
template: _.template( $('#client-item-template').text() ),
initialize: function() {
_.bindAll( this );
this.model.on( 'change', this.render );
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
});
From what I can gather from your code, you're only binding on the reset event of the collection.
According to the docs, Backbone.Collection uses the .update() method after fetching when you pass { update: true } as part of your fetch options.
Backbone.Collection.update() fires relevant add, change and remove events for each model. You'll need to bind to these as well and perform the relevant functions to update your UI.
In your case, you could bind to your existing addOneClient method to the add event on your collection.
In your ClientView class, you can bind to the change and remove events to re-render and remove the view respectively. Remember to use listenTo() so the ClientView object can easily clean-up the events when it remove()'s itself.
Related
I'm novice in Backbone.
I want to show a stock list, where user can open up any stock right from the list and change stock values. After that the whole list should refresh to show changed values.
So as I found out it's better not only to create collection but create collection and a list of stock models.
For this I created a stock collection view for main table and stock model view for adding rows to the table where each row is a single model.
So this is a collection view:
App.Views.StockTable = Backbone.View.extend({
...
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.template(this.collection));
this.addAll();
return this;
},
addOne: function(stock) {
var row = new App.Views.StockRow({
model: stock,
suppliers: this.suppliers
});
return this;
},
addAll: function() {
var suppliers = new App.Collections.Suppliers();
var that = this;
suppliers.fetch({
success: function() {
_.each(that.collection.toJSON(), that.addOne, that);
}
});
return this;
}
});
And this is my stock row view:
App.Views.StockRow = Backbone.View.extend({
el: 'tbody',
templateRow: _.template($('#stockRow').html()),
templatePreview: _.template($('#stockPreview').html()),
events: {
'click #open': 'open'
...
},
initialize: function() {
this.render();
},
render: function() {
this.$el.append(this.templateRow(this.model))
.append(this.templatePreview({
stock: this.model,
suppliers: this.suppliers
}));
return this;
},
open: function(e) {
var element = $(e.currentTarget);
element.attr('id', 'hide');
$('#stock' + element.data('id')).slideToggle('fast');
}
...
});
I wrote just a piece of code. The problem is that when I click on '#open' that event triggers many times (right the quantity elements in the collection). So when I catch e.currentTarget there are many similar objects.
What i do wrong?
I suspect you have multiple things going on here.
Without seeing your template, I suspect each of your StockRow rows are rendering a tag with the id="open". Since id values should be unique, use a class in your link (example: class="open"), and then reference that class in your click handler:
events: {
'click .open': 'open'
}
Next, since each instance of the StockRow already has a model instance associated with it, just use this.model instead of trying to look it up out of the data attribute of the currentTarget.
open: function () {
$('#stock' + this.model.id).slideToggle('fast');
}
But again, instead of using an id="stock" attribute in your template, use a class… say class="stock-preview". Then just look for that in your open…
open: function () {
this.$el.find('.stock-preview').slideToggle('fast');
}
The other piece that looks questionable to me is the call to this.addAll(); in the render method of the StockTable view. It is best practice to just have your render method render state, instead of having it trigger an ajax call to fetch the state.
For example, in your initialize you can setup some event handlers that react to your collection changing state (below is an incomplete example, just hoping to get you going in the right direction):
initialize: function (options) {
…
_.bindAll(this, 'render', 'renderRow');
this.collection.on('add', this.renderRow);
this.collection.on('reset', this.render);
},
render: function () {
this.$el.html(this.tableTemplateWithEmptyTBodyTags());
this.collection.each(this.renderRow);
return this;
},
renderRow: function () {
var row = new App.Views.StockRow({
model: stock,
suppliers: this.suppliers
});
this.$el.find('tbody').append(row.render().el);
return this;
}
And then outside the table view, you can do a suppliers.fetch(). Which when the response comes back should trigger the reset.
I am writing a backbone.js app, and I have a problem.
My collections do not fire events, can anyone spot the problem in the code bellow? I get the render-feedback, the initializer feedback.. but the append method is never called. I know that the "../app" returns a list with tro json items. And I can even see that these are being created in the collection.
Why do my event not get called?
window.TablesInspectorView = Backbone.View.extend({
tagName: "div",
initialize: function () {
console.log('Initializing window.TablesInspectorView');
// setup the tables
this.data = new Backbone.Collection();
this.data.url = "../app";
this.data.fetch();
// some event binds..
this.data.on("change", this.render , this);
this.data.on("add" , this.append_item, this);
},
render: function(){
console.log("render");
_.each(this.data.models, this.append_item);
},
append_item: function(item) {
console.log("appended");
}
});
According to my knowledge , the backbone fetch() is an asynchronous event and when it completes the reset event is triggered ,
When the models belonging to the collection (this.data) are modified , the change event is triggered, so im guessing you have not got that part correct.
so i would do something like this :
window.TablesInspectorView = Backbone.View.extend({
tagName: "div",
initialize: function () {
console.log('Initializing window.TablesInspectorView');
// setup the tables
this.data = new Backbone.Collection();
this.data.url = "../app";
this.data.fetch();
// some event binds..
this.data.on("reset", this.render , this); //change here
this.data.on("add" , this.append_item, this); // i dont see a this.data.add() in you code so assuming this was never called ?
},
render: function(){
console.log("render");
_.each(this.data.models, this.append_item);
},
append_item: function(item) {
console.log("appended");
}
});
I'm working on my first app using bbjs, after 10 tutorials and endless sources I am trying to come up with my code design.
I ask what is the best practice with views and templates. Also there is an events problem I am struggling with.
As I understand, the view is to be responsible for one element and its contents (and other sub-views).
For the code to be manageable, testable, etc.. the element/template is to be passed to the view on creation.
In my app Imho the view should hold the templates, because the visible element has many "states" and a different template for each state.
When the state changes, I guess its best to create a new view, but, is it possible for the view to update itself with new element?
App.Box = Backbone.Model.extend({
defaults: function() {
return {
media: "http://placehold.it/200x100",
text: "empty...",
type: "type1"
};
}
});
App.BoxView = Backbone.View.extend({
template: {},
templates: {
"type1": template('appboxtype1'),
"type2": template('appboxtype2')
},
events: {
'click .button': 'delete'
},
initialize: function(options) {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'destroy', this.remove);
this.render();
},
render: function() {
this.template = this.templates[ this.model.get("type") ];
// first method
this.$el.replaceWith( $($.parseHTML(this.template(this))) );
this.$el.attr("id", this.model.cid);
// second method
var $t_el = this.$el;
this.setElement( $($.parseHTML(this.template(this))) );
this.$el.attr("id", this.model.cid);
$t_el.replaceWith( this.$el );
this.delegateEvents();
//$('#'+this.model.cid).replaceWith( $(g.test.trim()) );
//! on the second render the events are no longer bind, deligateEvents doesn't help
return this;
},
// get values
text: function() { return this.model.get('text'); },
media: function() { return this.model.get('media'); },
delete: function() {
this.model.destroy();
}
});
Thanx! :)
Instead of trying to replace the view's root element ($el), just replace its content.
this.$el.html(this.template(this));
Events should still work then.
try this
render: function() {
html = '<div>your new html</div>';
var el = $(html);
this.$el.replaceWith(el);
this.setElement(el);
return this;
}
$.replaceWith will only replace the element in the DOM. But the this.$el still holds a reference to the now displaced old element. You need to call this.setElement(..) to update the this.$el field. Calling setElement will also undelegateEvents and delegateEvents events for you.
I came up with this solution: http://jsfiddle.net/Antonimo/vrQzF/4/
if anyone has a better idea its always welcome!
basically, in view:
var t_$el = this.$el;
this.$el = $($.parseHTML(this.template(this)));
this.$el.attr("id", this.cid);
if (t_$el.parent().length !== 0) { // if in dom
this.undelegateEvents();
t_$el.each(function(index, el){ // clean up
if( index !== 0 ){ $(el).remove(); }
});
t_$el.first().replaceWith(this.$el);
this.delegateEvents();
}
I have super-View who is in charge of rendering sub-Views. When I re-render the super-View all the events in the sub-Views are lost.
This is an example:
var SubView = Backbone.View.extend({
events: {
"click": "click"
},
click: function(){
console.log( "click!" );
},
render: function(){
this.$el.html( "click me" );
return this;
}
});
var Composer = Backbone.View.extend({
initialize: function(){
this.subView = new SubView();
},
render: function(){
this.$el.html( this.subView.render().el );
}
});
var composer = new Composer({el: $('#composer')});
composer.render();
When I click in the click me div the event is triggered. If I execute composer.render() again everything looks pretty the same but the click event is not triggered any more.
Check the working jsFiddle.
When you do this:
this.$el.html( this.subView.render().el );
You're effectively saying this:
this.$el.empty();
this.$el.append( this.subView.render().el );
and empty kills the events on everything inside this.$el:
To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.
So you lose the delegate call that binds events on this.subView and the SubView#render won't rebind them.
You need to slip a this.subView.delegateEvents() call into this.$el.html() but you need it to happen after the empty(). You could do it like this:
render: function(){
console.log( "Composer.render" );
this.$el.empty();
this.subView.delegateEvents();
this.$el.append( this.subView.render().el );
return this;
}
Demo: http://jsfiddle.net/ambiguous/57maA/1/
Or like this:
render: function(){
console.log( "Composer.render" );
this.$el.html( this.subView.render().el );
this.subView.delegateEvents();
return this;
}
Demo: http://jsfiddle.net/ambiguous/4qrRa/
Or you could remove and re-create the this.subView when rendering and sidestep the problem that way (but this might cause other problems...).
There's a simpler solution here that doesn't blow away the event registrations in the first place: jQuery.detach().
http://jsfiddle.net/ypG8U/1/
this.subView.render().$el.detach().appendTo( this.$el );
This variation is probably preferable for performance reasons though:
http://jsfiddle.net/ypG8U/2/
this.subView.$el.detach();
this.subView.render().$el.appendTo( this.$el );
// or
this.$el.append( this.subView.render().el );
Obviously this is a simplification that matches the example, where the sub view is the only content of the parent. If that was really the case, you could just re-render the sub view. If there were other content you could do something like:
var children = array[];
this.$el.children().detach();
children.push( subView.render().el );
// ...
this.$el.append( children );
or
_( this.subViews ).each( function ( subView ) {
subView.$el.detach();
} );
// ...
Also, in your original code, and repeated in #mu's answer, a DOM object is passed to jQuery.html(), but that method is only documented as accepting strings of HTML:
this.$el.html( this.subView.render().el );
Documented signature for jQuery.html():
.html( htmlString )
http://api.jquery.com/html/#html2
When using $(el).empty() it removes all the child elements in the selected element AND removes ALL the events (and data) that are bound to any (child) elements inside of the selected element (el).
To keep the events bound to the child elements, but still remove the child elements, use:
$(el).children().detach(); instead of $(.el).empty();
This will allow your view to rerender successfully with the events still bound and working.
I have a view which doesn't seem to want to render as the model's change event is not firing.
here's my model:
var LanguagePanelModel = Backbone.Model.extend({
name: "langpanel",
url: "/setlocale",
initialize: function(){
console.log("langselect initing")
}
})
here's my view:
var LanguagePanelView = Backbone.View.extend({
tagName: "div",
className: "langselect",
render: function(){
this.el.innerHTML = this.model.get("content");
console.log("render",this.model.get(0))
return this;
},
initialize : function(options) {
console.log("initializing",this.model)
_.bindAll(this, "render");
this.model.bind('change', this.render);
this.model.fetch(this.model.url);
}
});
here's how I instantiate them:
if(some stuff here)
{
lsm = new LanguagePanelModel();
lsv = new LanguagePanelView({model:lsm});
}
I get logs for the init but not for the render of the view?
Any ideas?
I guess it's about setting the attributes of the model - name is not a standard attribute and the way you've defined it, it seems to be accessible directly by using model.name and backbone doesn't allow that AFAIK. Here are the changes that work :) You can see the associated fiddle with it too :)
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "Some test content" //just 'cause there wasn't anything to fetch from the server
},
url: "/setlocale",
initialize: function(){
console.log("langselect initing"); //does get logged
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'), //added here directly so that content can be seen in the actual div
initialize : function(options) {
console.log("initializing",this.model);
_.bindAll(this, "render");
this.render(); //calling directly since 'change' won't be triggered
this.model.bind('change', this.render);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c); //for UI visibility
console.log("render",this.model.get(0)); //does get logged :)
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
}); //end ready
UPDATE:
You don't need to manually trigger the change event - think of it as bad practice. Here's what the backbone documentation says (note: fetch also triggers change!)
Fetch
model.fetch([options])
Resets the model's state from the server.
Useful if the model has never been populated with data, or if you'd
like to ensure that you have the latest server state. A "change" event
will be triggered if the server's state differs from the current
attributes. Accepts success and error callbacks in the options hash,
which are passed (model, response) as arguments.
So, if the value fetched from the server is different from the defaults the change event will be fired so you needn't do it yourself. If you really wish to have such an event then you can use the trigger approach but custom name it since it's specific to your application. You are basically trying to overload the event so to speak. Totally fine, but just a thought.
Change
model.change()
Manually trigger the "change" event. If you've been
passing {silent: true} to the set function in order to aggregate rapid
changes to a model, you'll want to call model.change() when you're all
finished.
The change event is to be manually triggered only if you've been suppressing the event by passing silent:true as an argument to the set method of the model.
You may also want to look at 'has changed' and other events from the backbone doc.
EDIT Forgot to add the updated fiddle for the above example - you can see that the alert box pops up twice when the model is changed by explicitly calling set - the same would happen on fetching too. And hence the comment on the fact that you "may not" need to trigger 'change' manually as you are doing :)
The issue was resolved my adding
var LanguagePanelModel = Backbone.Model.extend({
//adding custom attributes to defaults (with default values)
defaults: {
name: "langpanel",
content: "no content",
rawdata: "no data"
},
events:{
//"refresh" : "parse"
},
url: "/setlocale",
initialize: function(){
log("langselect initing");
//this.fetch()
},
parse: function(response) {
this.rawdata = response;
// ... do some stuff
this.trigger('change',this) //<-- this is what was necessary
}
})
You don't need attributes to be predefined unlike PhD suggested. You need to pass the context to 'bind' - this.model.bind('change', this.render, this);
See working fiddle at http://jsfiddle.net/7LzTt/ or code below:
$(document).ready(function(){
var LanguagePanelModel = Backbone.Model.extend({
url: "/setlocale",
initialize: function(){
console.log("langselect initing");
}
});
var LanguagePanelView = Backbone.View.extend({
el: $('#somediv'),
initialize : function(options) {
console.log("initializing",this.model);
// _.bindAll(this, "render");
//this.render();
this.model.bind('change', this.render, this);
//this.model.fetch(this.model.url);
},
render: function(){
var c = this.model.get("content");
alert(c);
$(this.el).html(c);
console.log("render",this.model.get(0));
return this;
}
});
var lpm = new LanguagePanelModel();
var lpv = new LanguagePanelView({model:lpm});
lpm.set({content:"hello"});
}); //end ready