Re-Rendering & Appending Child View's HTML to DOM Seems to Not Re-Apply Child View's Events - backbone.js

In the Marionette docs for CompositeView, it describes overriding appendHTML to customize the target the HTML of each itemView should be added to using jQuery's append.
Using a similar line of thinking, if I have two ItemView objects, a Parent and a Child, and Parent's template has an empty target <div class="target"></div> I'd like to inject Child's template inside of. I can use jQuery's html with an onRender in Parent to do this.
Throughout the course of the Parent's life, I want to flush out or replace the contents of .target with something else. If I later want to re-render Child into .target (since it may render it's template differently based on user interaction since the first rendering), I can use the same logic:
Render the Child template
Set .target's contents to Child's el with jQuery's html
The issue is, once this second rendering of Child has occurred, any events from the Child view seem to be lost.
Here is a concrete example of what I'm describing:
The HTML
<script type="template" id="parent">
<p><a class="re-render" href="javascript://">Re-Render</a></p>
<div class="target"></div>
</script>
<script type="template" id="child">
<p>The Link</p>
</script>
<div id="main"></div>
The Javascript
var Views = {};
Views.Child = Backbone.Marionette.ItemView.extend({
template: '#child',
events: {
'click a': 'changeBg'
},
changeBg: function() {
this.$el.css('background-color', '#'+Math.floor(Math.random()*16777215).toString(16));
}
});
Views.Parent = Backbone.Marionette.ItemView.extend({
template: '#parent',
childView: undefined,
ui: {
target: '.target'
},
events: {
'click .re-render': 'onRender'
},
initialize: function() {
this.childView = new Views.Child();
},
onRender: function() {
this.childView.render();
this.ui.target.html(this.childView.el);
this.childView.$el.css('background-color', 'transparent');
}
});
var App = new Backbone.Marionette.Application();
App.addRegions({
mainRegion: "#main"
})
App.mainRegion.show(new Views.Parent());
Clicking The Link in Child at first works great. Once Re-Render is clicked in Parent, the Child click event is never re-applied to the newly rendered version of the Child's template. How can I ensure the Child template's events will be re-applied each time the Child is rendered?
You can find a jsFiddle for this here.

You should call .delegateEvents() on the child view after it has been re-rendered:
onRender: function() {
this.childView.render();
this.ui.target.html(this.childView.el);
this.childView.delegateEvents();
this.childView.$el.css('background-color', 'transparent');
}
This is how to solve it in vanilla Backbone. I don't know if Backbone.Marionette has another way of handling the problem, but in Marionette terms you could add the delegateEvents call to the child view's onRender method to encapsulate the re-renderability.
Views.Child = Backbone.Marionette.ItemView.extend({
//...
onRender: function() {
this.delegateEvents();
}
});

Related

Backbone.js: undelegateEvents not removing events

In the following code:
HTML
<div id="myView">
<button id="test_button">
Test Button
</button>
<ul id="output"></ul>
</div>
JavaScript
var myView = Backbone.View.extend({
initialize: function() {
// why doesn't this remove the previously delegated events?
this.undelegateEvents();
this.delegateEvents({
'click #test_button': 'buttonClicked'
});
},
// this event fires twice for one button click
buttonClicked: function() {
$("#output").append('<li>Button was clicked</li>');
}
});
$(document).ready(function(){
new myView({el: "#myView"});
// instantiate view again
new myView({el: "#myView"});
});
why does
this.undelegateEvents();
in the initialize() method of the Backbone View not remove the previously delegated events from the previous instantiation of the View?
JSFiddle example of above code: https://jsfiddle.net/billb123/o43zruea/28/
I'll try not to shout but please stop trying to bind views to existing elements. Let the view create and own its own el, then call view.remove() to kill it off before replacing it. This simple change solves so many problems with view events that you should always think twice (and twice more) if you don't do it this way.
In your case, you'd have HTML like this:
<script id="t" type="text/x-underscore">
<div id="myView">
<button id="test_button">
Test Button
</button>
</div>
</script>
<div id="container">
</div>
<ul id="output"> <!-- This is outside the container because we're going to empty and refill it -->
</ul>
And your JavaScript would look like this:
var myView = Backbone.View.extend({
events: {
'click #test_button': 'buttonClicked'
},
render: function() {
this.$el.html($('#t').html());
return this;
},
buttonClicked: function() {
$("#output").append('<li>Button was clicked</li>');
}
});
$(document).ready(function(){
var v = new myView();
$('#container').append(v.render().el);
v.remove(); // <----------------- Clean things up before adding a new one
v = new myView();
$('#container').append(v.render().el);
});
Points of interest:
Create the view then render it then put it on the page.
Call remove on the view when you're done with it.
The view goes inside the container. The caller owns the container, the view owns its el.
There are no delegateEvents or undelegateEvents calls anywhere. The presence of those almost always point to structural problems in your application IMO.
Each view is self contained: the outside world doesn't play with anything inside the view and the view keeps its hands to itself.
Updated fiddle: https://jsfiddle.net/bp8fqdgm/
But why didn't your attempted undelegateEvents do anything? undelegateEvents looks like this:
undelegateEvents: function() {
if (this.$el) this.$el.off('.delegateEvents' + this.cid);
return this;
},
The cid is unique per view instance so each view instance uses its own unique namespace for events that delegateEvents binds. That means that this:
this.undelegateEvents();
this.delegateEvents();
is saying:
Remove the events that this instance of the view has bound. These events will be found in the the '.delegateEvents' + this.cid namespace where cid is unique for each view instance.
Bind the events that this instance of the view defines (or the events in the delegateEvents call). These events will be attached using the '.delegateEvents' + this.cid namespace.
So your undelegateEvents call is removing events but not all of them, only the specific event bindings that that view instance adds are removed.
Your this.undelegateEvents() call doesn't actually accomplish anything because it is in the wrong place and called at the wrong time. If the new View caller did the undelegateEvents call:
var v = new myView({el: "#myView"});
v.undelegateEvents();
new myView({el: "#myView"});
then it would happen in the right place and at the right time. Of course this means that your router needs to keep track of the current view so that it can currentView.undelegateEvents() at the right time; but if you're doing that then you'd be better off (IMO) taking the approach I outlined at the top of the answer.

adding a class to Handlebar template during initialise

I want to add a class to one of the elements in a Handlebar template while initialising the view.
Here is the where I initialise the LayoutView
export default LayoutView.extend({
className: 'LandingPageHeaderDetail',
template: fs.readFileSync(`${__dirname}/LandingPageHeaderDetail.hbs`, 'utf8'),
initialize: function (options) {
this.setMenu(options)
},
setMenu (options) {
// in here I want to add a className to one of the elements
// in the template file
// for example template = <ul><li id="id1">dkjfls</li><li id="id2">kdjfkls</li>
// if (options == id1) { add class x to element} else { add class to y element }
}
My question is how do I navigate the template tree, find the element I'm looking for and add a class to it.
I've tried using jQuery selectors as follows: $('#id1') but it returns null, probably because the template hasn't rendered yet. Any ideas?
You can use Marionette's serializeData function.
initialize: function(options){
this.myOptions = options;
},
serializeData: function(){
return {id: this.myOptions};
}
Then you can create a helper for Handlebars using the answer from this question: Handlebars.js if block helper ==
Then in your template, put the actual logic to apply the class:
<ul>
<li id="id1" {{#if_eq id "id1"}}class="classname"{{/if_eq}}>dkjfls</li>
<li id="id2" {{#if_eq id "id2"}}class="classname"{{/if_eq}}>kdjfkls</li>
</ul>
As you said, you can't work with the template inside initialize function cause the template is not rendered yet. Use Render event, it's triggered after the view has been rendered.
Marionette.View.extend({
onRender: function(){
// manipulate the `el` here. it's already
// been rendered, and is full of the view's
// HTML, ready to go.
this.setMenu();
},
setMenu: function(){
// now i can manipulate the template...
}
});
Other solution would be to use serializeModel or templateContext.

Marionette and Backbone. Rendering javascript slider in View

This is the code:
NewEntry_CategoryView = Backbone.Marionette.ItemView.extend({
template: "#NewEntry_Category-template",
tagName: "p",
initialize: function () {
$("#sliderContainer").slider();
}
});
NewEntry_CategoriesView = Backbone.Marionette.CompositeView.extend({
template: "#NewEntry_Categories-template",
tagName: "div",
itemView: NewEntry_CategoryView,
itemViewContainer: '#categoryContainer',
appendHtml: function (collectionView, itemView) {
collectionView.$("#categoryContainer").append(itemView.el);
}
});
Why does the jquery ui slider not render when I show the NewEntry_CategoriesView ?
DOM events/manipulation like slide() won't have any effect on the view object's initialization because there is no such DOM element available yet.
Instead, you need to listen to dom:refresh of the view to manipulate its DOM element.
So, just put the code in onDomRefreshin your ItemView
onDomRefresh: function(){ $('#sliderContainer').slide() };
This above is a direct fix. But there are two more things to improve:
Don't call other div outside of this view when possible. In this case, if #sliderContainer belongs to another view, send an event to allow it slide itself. This is not the job of CategoryView. If it is inside current view, refer it with this.$el.find(".some-div") or better yet ui object.
Your collectionView's appendHtml is unnecessary. Marionette also takes of this common case.

How to set .el to div which is in underscore.js template?

It is pretty basic thing but I still can't find the answer. I need to set View's el: to div which is in underscore.js template.
<script id="product" type="text/template">
<div class="productInfo"></div>
<div class="prices"></div>
<div class="photos"></div>
</script>
The first view renders the product template. I need to render other Views to divs in this template. I don't know how to set el:, because el: '.prices' just don't work with divs in template.
This Views structure is similar to How to handle initializing and rendering subviews in Backbone.js?. But I use template instead of rendering to existing divs.
So the problem is using a CSS selector string for this.el won't find anything if the matching <div> is not attached to the page's DOM. In the case of you <script> tag template, the contents of the <script> tag are not attached DOM nodes, there are just a single text node.
One option given your HTML would be to just forget about the <script> tag and put your empty <div> tags straight into the HTML. They are empty and thus should be harmless and invisible until you actual render some content within them. If you do that, el: '.productInfo:first' should work fine.
Other than that, you'll need to put logic into your parent view along these lines:
Render the template into a detached DOM node
Search that detached DOM node for subview divs
Map the subview div to the corresponding backbone view subclass
instantiate and render the subview, then use something like this.$el.find('.productInfo').replaceWith(productInfoView.el) to put the rendered HTML into the parent view at the right location
My general comment is that views should render to detached DOM nodes and leave it to other components such as the router or layout managers to decide where in the real DOM they get attached. I think this makes the views more reusable and testable.
Render the parent view, then assign the '.prices' as the el of the child:
var ParentView = Backbone.View.extend({
render : function() {
var html='<h1>Parent View</h1><div class="productInfo"></div><div class="prices"></div><div class="photos"></div>';
this.$el.html(html);
var prices = new PricesView({
el : this.$('.prices')
});
prices.render();
}
});
var PricesView = Backbone.View.extend({
render : function() {
var html='<h2>Prices View</h1>';
this.$el.html(html);
}
});
// Create a parent view instance and render it
var parent = new ParentView({
el : $('.parent')
});
parent.render();
​
Working example on jsfiddle: http://jsfiddle.net/JpeJs/
from version 0.9.9, backbone alaws you to define the el property of a view as a function :
When declaring a View, options, el and tagName may now be defined as functions, if you want their values to be determined at runtime.
Assuming that the subviews are created after the main view, this might help you if your subviews are aware of their parent :
SubView = Backbone.View.extend({
el : function(){
return this.parent.$('.prices');
}
});
var subViewInstance = new SubView({parent : theParentView});

Backbone.js turning off wrap by div in render

I have model Post and collection Posts. And want to make form with list of all post in <select id="multi" multiple="multiple">. So i have to make a PostView render inside my #multi with just this template:
<option value=""><%= title %></option>
But finally I get it wrapped with div. Is there any solution for not wrapping this template with <div>?
If you don't define an el (or tagName) for the view (in the class or during instantiation) the view will be placed inside a div tag. http://documentcloud.github.com/backbone/#View-el
var PostView = Backbone.View.extend({
tagName: 'option'
});
UPDATE
Starting v0.9.0, Backbone has view.setElement(element) to get this done.
var PostView = Backbone.View.extend({
initialize: function() {
var template = _.template('<option value=""><%= title %></option>');
var html = template({title: 'post'});
this.setElement(html);
}
});
If you don't want to have the view wrap your HTML, you'll have to do a few things:
Replace this.el entirely
Call delegateEvents on the new el
render: function(){
var html = "some foo";
this.el = html;
this.delegateEvents(this.events);
}
Since Backbone generates a div or other tag (based on your tagName setting for the view), you have to replace it entirely. That's easy to do. When you do that, though, you lose your declared events because Backbone uses jQuery's delegate under the hood to wire them up. To re-enable your declared events, call delegateEvents and pass in your events declarations.
The result is that your view.el will be the <option> tag that you want, and nothing more.
In version 0.9.0, Backbone introduced view.setElement(element) to handle this operation.

Resources