Backbone refresh view events - javascript

In my view I don't declare this.el because I create it dinamically, but in this way the events don't fire.
This is the code:
View 1:
App.Views_1 = Backbone.View.extend({
el: '#content',
initialize: function() {
_.bindAll(this, 'render', 'renderSingle');
},
render: function() {
this.model.each(this.renderSingle);
},
renderSingle: function(model) {
this.tmpView = new App.Views_2({model: model});
$(this.el).append( this.tmpView.render().el );
}
});
View 2:
App.Views_2 = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
this.el = $('#template').tmpl(this.model.attributes); // jQuery template
return this;
},
events: {
'click .button' : 'test'
},
test: function() {
alert('Fire');
}
});
});
When I click on ".button" nothing happens.
Thanks;

At the end of your render() method, you can tell backbone to rebind events using delegateEvents(). If you don't pass in any arguments, it will use your events hash.
render: function() {
this.el = $('#template').tmpl(this.model.attributes); // jQuery template
this.delegateEvents();
return this;
}

As of Backbone.js v0.9.0 (Jan. 30, 2012), there is the setElement method to switching a views element and manages the event delegation.
render: function() {
this.setElement($('#template').tmpl(this.model.attributes));
return this;
}
Backbone.View setElement: http://backbonejs.org/#View-setElement
setElementview.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use
setElement, which will also create the cached $el reference and move
the view's delegated events from the old element to the new one.
Dynamically creating your views in this fashion has it's pros and cons, though:
Pros:
All of your application's HTML markup would be generated in templates, because the Views root elements are all replaced by the markup returned from the rendering. This is actually kind of nice... no more looking for HTML inside of JS.
Nice separation of concerns. Templates generate 100% of HTML markup. Views only display states of that markup and respond to various events.
Having render be responsible for the creation of the entire view (including it's root element) is in line with the way that ReactJS renders components, so this could be a beneficial step in the process of migrating from Backbone.Views to ReactJS components.
Cons: - these are mostly negligible
This wouldn't be a painless transition to make on an existing code base. Views would need to be updated and all templates would need to have the View's root elements included in the markup.
Templates used by multiple views could get a little hairy - Would the root element be identical in all use cases?
Prior to render being called, the view's root element is useless. Any modifications to it will be thrown away.
This would include parent views setting classes/data on child view elements prior to rendering. It is also bad practice to do this, but it happens -- those modifications will be lost once render overrides the element.
Unless you override the Backbone.View constructor, every view will unnecessarily delegate it's events and set attributes to a root element that is replaced during rendering.
If one of your templates resolves to a list of elements rather than a single parent element containing children, you're going have a bad time. setElement will grab the first element from that list and throw away the rest.
Here's an example of that problem, though: http://jsfiddle.net/CoryDanielson/Lj3r85ew/
This problem could be mitigated via a build task that parses the templates and ensures they resolve to a single element, or by overriding setElement and ensuring that the incoming element.length === 1.

Related

How to properly destroy view on backbone?

So Im new at backbone, and Im trying to make a single page app, Im using routes to manage certain things, and I want to remove a view when the user gets to another route
Im using this method to destroy the view
destroy_view: function() {
// COMPLETELY UNBIND THE VIEW
this.undelegateEvents();
this.$el.removeData().unbind();
// Remove view from DOM
this.remove();
Backbone.View.prototype.remove.call(this);
}
also this is my route element
Router = Backbone.Router.extend({
routes: {
'':'index',
'#':'index',
'events/*event' : 'events'
},
index: function(){
this.indexView = new VistaIndex();
},
events: function(params) {
if( this.indexView )
this.indexView.destroy_view()
this.eventView = new EventView({currentEvent: params})
}
});
the problem with this is that if I do this the app crashes, so what do you recommend me to do :)
Here’s how I do it:
Backbone.View.extend({
//some other view stuff here...
destroy: function () {
this.undelegateEvents();
this.$el.removeData().unbind();
this.remove();
//OR
this.$el.empty();
}
});
First we want to make sure we’re removing all delegated events (the ones in the events:{"event selector": "callback"} hash). We do this so we can avoid memory leaks and not have mystery bindings that will fire unexpectedly later on. undelegateEvents() is a Backbone.View prototype function that removes the view’s delegated events. Simple.
Next we want to cleanup any data in the view object that is hanging around and unbind any events that we bound outside the events hash. jQuery provides a removeData() function that allows us to to do that.
You may also have bound event listeners to your view chain unbind() with no arguments to remove all previously-attached event handlers from your $el. this.$el.removeData().unbind();
Now you may want to do one of two things here. You may want to remove your view element completely OR you just want to remove any child elements you’ve appended to it during it’s life. The latter would be appropriate if, for example, you’ve set the $el of your view to be some DOM element that should remain after your view behavior is complete
In the former case, this.remove() will obliterate your view element and it’s children from the DOM.
In the later case, this.$el.empty() will remove all child elements.
Check out this fiddle if you want to fool around with my solution.
http://jsfiddle.net/oakley349/caqLx10x/

marionette.js vs Backbone updating DOM

I have noticed there is a different, the way DOM been updated by Marionette comparing with Backbone. I have created two simple fiddles. One using Backbone and other one based on marionette. Both examples has a helper method call processDom and that method simply throw an error after iterating 50 times.
However in backbone example elements been appended to DOM till die() method fires. But in marionette based example DOM has not been updated at all. It would be great if someone can explain how this works. I wonder marionette internally using a virtual dom kind of a technique.
Render method in marionette example
render: function () {
var viewHtml = this.template({
'contentPlacement': 'Sydney'
});
this.$el.html(viewHtml);
this.processDom(this.$el);
this.postRender();
}
Render method in backbone example
render: function () {
var template = Handlebars.compile($('#sample-template').html());
var viewHtml = template({
'contentPlacement': 'Sydney'
});
this.$el.html(viewHtml);
this.processDom(this.$el);
this.postRender();
},
Links to fiddle examples
http://jsfiddle.net/samitha/v5L7c2t5/7/
http://jsfiddle.net/samitha/pc2cvmLs/7/
In general for post processing purposes you could use onRender of Marionette.ItemView. It's not a good practice to rewrite Marionette.ItemView.render.
Rendering of views inside the regions for Marionette is handled a bit different as in Backbone case.
When you rendering Backbone.View - your element will attach itself to the DOM's $('#search-container'), and in render method it will operate with already attached element so you can see the changes.
When you rendering Marionette.ItemView with Marionette.Region.show method, Marionette.Region already attached to the DOM and it need to render appropriate view (in your case ItemView) and only after that step it will attach it to the DOM and will set the ItemView as currentView.
You can see from source of Marionette.Region.show that it attaches view after render is called. In your case render will throw error and it will never be attached to the DOM.
To understand it deeper lets look at the 2 methods which are responsible for attaching/creating views in BackboneView. Marionette uses the same method for Marionette.ItemView.
_ensureElement: function() {
if (!this.el) { // case when el property not specified in view
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
// creating new jQuery element(tagNam is div by default) with attributes specified
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else { // case when el property exists
this.setElement(_.result(this, 'el'), false);
}
}
And
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
// here is all magic
// if element is instance of Backbone.$, which means that el property not specified
// or it's already jquery element like in your example( el: $('#search_container')) with Backbone.
// this.$el will be just a jQuery element or already attached to the DOM jQuery element
// in other case it will try to attach it to the DOM.
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
As you can see from comments all magic is in a few lines of code, and that's why I love it.

Backbone.js render view once again or re-create?

Currently I am dealing with zombies in my backbone.js application. I have read this exelent article http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/ about zombies and extended my project with this:
Backbone.View.prototype.close = function(){
this.remove();
this.unbind();
if (this.onClose){
this.onClose();
}
}
My question is, how to revert this close process? Can I just call render on the object or do I have to re initiate the object by just overwriting it with a new instance?
The this.remove() call removes the view's el from the DOM:
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
so you'd have to recreate that and rebind all the DOM events. You'll also lose all the Backbone event bindings during the this.unbind() and this.stopListening() calls. Then there's whatever your onClose does (if you have one) so you'd need "undo onClose" methods.
Basically, don't try to re-use views, just destroy them (with proper cleanup) and create new ones. Your views should be lightweight enough that killing and rebuilding them shouldn't matter.

Backbone.js: Should .render() and .remove() be able to reverse each other?

Because Backbone.js is pretty flexible, I am wondering about the best approach for certain things. Here I'm wondering if I'm supposed to build my application's views so that '.render()' and '.remove()' correctly reverse each other.
At first, the way that seems cleanest is to pass the view a ID or jQuery element to attach to. If things are done this way though, calling '.render()' will not correctly replace the view in the DOM, since the main element is never put back in the DOM:
App.ChromeView = Backbone.View.extend({
render: function() {
// Instantiate some "sub" views to handle the responsibilities of
// their respective elements.
this.sidebar = new App.SidebarView({ el: this.$(".sidebar") });
this.menu = new App.NavigationView({ el: this.$("nav") });
}
});
$(function() {
App.chrome = new App.ChromeView({ el: $("#chrome") });
});
It seems preferable to me to set it up so that .remove() and .render() are exact opposites:
App.ChromeView = Backbone.View.extend({
render: function() {
this.$el.appendTo('body');
this.sidebar = new App.SidebarView({ el: this.$(".sidebar") });
this.menu = new App.NavigationView({ el: this.$("nav") });
}
});
$(function() {
App.chrome = new App.ChromeView();
});
What does the Backbone.js community say? Should .remove() and .render() be opposite sides of the same coin?
I prefer that render does NOT attach the view's element to the dom. I think this promotes loose coupling, high cohesion, view re-use, and facilitates unit testing. I leave attaching the rendered element to a container up to either the router or a main "layout" type container view.
The nice thing about remove is that it works without the view having knowledge of the parent element, and thus is still loosely coupled and reusable. I definitely don't like to put random DOM selectors from my layout HTML (#main or whatever) into my views. Definitely bad coupling there.
I will note that in certain annoying situations, some things like the chosen jQuery plugin require some code to run AFTER the element has been attached to the DOM. For these cases I usually implement a postAttach() callback in the view and try to keep the amount of code there as small as possible.
Yes, the in-house View.remove() is very agressive.
For the propose of re-create the View again using an external el I am used to rewrite it like this:
remove: function(){
this.$el.empty();
return this;
}
But I don't think the framework should implement magic behavior to avoid this external DOM elements deletion.
This framework behavior is aggressive, ok, but it is very cheap to customize it when needed as we see above.
What about this? If we just have .initialize and .render take a parentSelector property, we can do this and end up with a usage that is:
Loosely coupled
Reversable .remove()/.render()
Single method
instantiation & rendering for the calling method
eg:
// Bootstrap file
curl(['views/app']).then(
function(App){
app = new App('body');
});
// view/app.js
define([
'text!views/app.tmpl.html'
, 'link!views/app.css'
]
, function (template) {
var App
// Set up the Application View
App = Backbone.View.extend({
// Standard Backbone Methods
initialize: function (parentSel) {
console.log('App view initialized')
if (parentSel) { this.render(parentSel) }
}
, render: function (parentSel) {
if (parentSel) { this._sel = parentSel } // change the selector if render is called with one
if (!this._sel) { return this } // exit if no selector is set
this.$el.appendTo(this._sel)
this.$el.html(
this.compiledTemplate({ 'content':'test content' })
);
return this
}
// Custom Properties
, compiledTemplate: _.template(template)
})
return App
});
// External usage
// I can call .remove and .render all day long now:
app.remove()
app.render()
app.remove()

How to specify a method callback when a Backbone View is inserted into the DOM?

I need to run a layout script as soon as my views are inserted into the DOM. So...
$(".widgets").append(widgets.render().el)
$(".widgets .dashboard").isotope # <-- This needs to be called whenever new widgets are inserted
The problem is I have to insert new widgets a few different views and re-call this script a few different places, which is not DRY. I am wondering how I can define the isotope in the View class.
Would it be a good idea to define an event listener to watch for append into the ".widgets" and to run the script? Is there a built in way of building views that are smart about when they are added to the DOM?
(For that matter, it would be also useful to define a callback for when a View is removed from the DOM.)
How about calling the isotope each time the view is rendered? You'll need to be careful to call render() only after the widget is injected, but this ought to take care of your problem:
//in Backbone.view.extend({
initialize: function() {
// fix context for `this`
_.bindAll(this);
},
render: function() {
// .. do rendering..
this.isotope();
return this;
}
// }) // end .extend
use:
var self = this;
this.$el.on('DOMNodeInserted', function(evt){
self.isotope();
$(evt.target ).stopPropagation();
})

Categories