Marionette bubble event from itemview to parent layoutview? - backbone.js

I have a layout view with a region, in that region I have a item view that triggers an event but it doesn't seem to be bubbled up to the layout view. Am I doing something wrong or is this designed behavior? I assume the itemview prefix is not added as the parent view is not a collection view? Either way the event is never bubbled to the layout view.
layoutView = Marionette.Layout.extend({
template: "#layout-template",
regions: {
titleRegion: "#job-title-region"
},
triggers: {
"save:clicked" : "onSaveClicked"
},
onSaveClicked: function (args) {
alert('Clicked');
}
});
childview = Marionette.ItemView.extend({
template: "#child-template",
triggers: {
"click .js-save": "save:clicked"
}
});
UPDATE:
See this fiddle http://jsfiddle.net/7ATMz/11/ I managed to get the layout view to listen to the child event but I have to wire it up outside of the layout view itself and break encapsulation. Can I do this in the layout view in anyway?
Thanks,
Jon

Triggers don't quite work like that: your layout is using them wrong. Triggers are a convenience to raise an event signal given a certain interaction (e.g. a click).
What you want is to use triggerMethod (https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.functions.md#marionettetriggermethod) to trigger a function in your layout. See http://jsfiddle.net/ZxEa5/ Basically, you want this in your show function:
childView.on("btn:clicked", function(){
layout.triggerMethod("childView:btn:clicked");
});
And in your layout:
onChildViewBtnClicked: function(){
https://leanpub.com/marionette-gentle-introduction
});
Event bubbling only happens automagically with collection?composite views because they're tightly associated with their item views. If you want a layout to monitor one of its child views, you need to set that up on your own.
Shameless plug: if you want to learn more about how to structure and clean up your code with Marionette, you can check out my book (https://leanpub.com/marionette-gentle-introduction) where this type of concept (and its applications) is explained in more detail.

I'm not sure when this Marionette feature was introduced, but a much simpler solution would be using the childEvents hash: http://marionettejs.com/docs/v2.4.1/marionette.layoutview.html#layoutview-childevents
...
childEvents: {
"save:clicked" : "onSaveClicked"
},
...
You could also directly bind the child event to a function outside of LayoutView, if it makes more sense, like this:
layout.on('childview:save:clicked', function(childView) {
alert('clicked');
}

I recommend using Backbone.Courier for this type of need: https://github.com/rotundasoftware/backbone.courier

I implemented a solution for a similar problem as follows. First, I wrote a new method right into the Marionette.View prototype:
Marionette.View.prototype.bubbleMethod = function () {
var args = _.toArray(arguments)
var event = args.shift()
var bubble = event + ':bubble'
this.triggerMethod.apply(this, [ event ].concat(args))
this.triggerMethod.apply(this, [ bubble ].concat(args))
}
That will call the regular triggerMethod from Marionette twice: once with your event name as it is intended to be handled, and a second one which is easily recognizable by specialized views, designated to bubble events up.
Then you will need such specialized view and bubble up events that are meant to be bubbled up. You must be careful not to dispatch events like close (or any Marionette events at all) in behalf of other views, because that will cause all sorts of unpredictable behaviors in Regions and Views. The :bubble suffix allows you to easily recognize what's meant to bubble. The bubbling view might look like this:
var BubblingLayout = Marionette.Layout.extend({
handleBubbles: function (view) {
var bubble = /:bubble$/
this.listenTo(view, 'all', function () {
var args = _.toArray(arguments)
var event = args.shift()
if (event.match(bubble)) {
event = event.replace(bubble, '')
this.bubbleMethod.apply(this, [ event ].concat(args))
}
}, this)
}
})
The last thing you need to make sure is to be able to bubble events across regions (for Layouts and modules with custom region managers). That can be handled with the show event dispatches from a region, like this:
var BubblingLayout = Marionette.Layout.extend({
regions: {
sidebar: '#sidebar'
},
initialize: function () {
this.sidebar.on('show', this.handleBubbles, this)
},
handleBubbles: function (view) {
var bubble = /:bubble$/
this.listenTo(view, 'all', function () {
var args = _.toArray(arguments)
var event = args.shift()
if (event.match(bubble)) {
event = event.replace(bubble, '')
this.bubbleMethod.apply(this, [ event ].concat(args))
}
}, this)
}
})
The last part is to make something actually bubble up, which is easily handled by the new bubbleMethod method:
var MyView = Marionette.ItemView.extend({
events: {
'click': 'clickHandler'
},
clickHandler: function (ev) {
// do some stuff, then bubble something else
this.bubbleMethod('stuff:done')
}
})
var BubblingLayout = Marionette.Layout.extend({
regions: {
sidebar: '#sidebar'
},
initialize: function () {
this.sidebar.on('show', this.handleBubbles, this)
},
onRender: function () {
var view = new MyView()
this.sidebar.show(view)
},
handleBubbles: function (view) {
var bubble = /:bubble$/
this.listenTo(view, 'all', function () {
var args = _.toArray(arguments)
var event = args.shift()
if (event.match(bubble)) {
event = event.replace(bubble, '')
this.bubbleMethod.apply(this, [ event ].concat(args))
}
}, this)
}
})
Now you can handle bubbled events from any place in your code where you can access an instance of BubblingLayout.

Why not just allow the click event to bubble up the DOM hierarchy and handle it in your Layout view? Something like this (fiddle here):
var MainView = Marionette.Layout.extend({
template: "#layout-template",
regions: {
childRegion: "#childRegion"
},
events: {
'click #btn': 'handleButtonClick'
},
handleButtonClick: function() {
alert('btn clicked in child region and bubbled up to layout');
}
});
var ChildView = Marionette.ItemView.extend({
template: "#child-template"
/*
triggers: {
"click #btn": "btn:clicked"
}*/
});

Related

Two Views Sharing an Event

I've been thrown into a Backbone code base and one of the modifications I need to make requires duplicating a text element with typeahead. Rather than copy and paste code, I'd like to re-use the event code but as I know hardly anything about Backbone I'm not sure how this should be done. Should it be a helper? If so, where do I put the helper code so it can be used by both views? I'd rather not attempt view inheritance if at all possible because I'd like to keep the changes as simple and minimal as possible.
events: {
// all other events removed for conciseness.
'typeahead:selected #ud_producerid': 'producerChanged'
}
I need the same event with the identical functionality in the producerChanged function as well as the setupBindings code that wires up the typeahead to work in 2 different views.
I know you said you didn't want to use inheritance here but it is easy in Backbone and well suited to the task.
var TypeaheadBase = Backbone.View.extend({
events: {
'typeahead:selected #ud_producerid': 'producerChanged'
},
producerChanged: function(e) {
...
},
anotherBaseMethod: function() {
...
}
});
var TypeaheadBaseA = TypeaheadBase.extend({
someOtherAMethod: function() {
...
},
// You can do some extra functionality on `producerChanged`.
// (Or you can override by not calling the Base prototype).
producerChanged: function() {
TypeaheadBase.prototype.producerChanged.apply(this, arguments);
// Do some additional stuff.
}
});
var TypeaheadBaseB = TypeaheadBase.extend({
// You can also extend things like events, which could be a hash (Object).
events: function() {
var parentEvents = _.result(TypeaheadBase.prototype, 'events');
return _.extend({}, parentEvents, {
'click a': 'someClickEvent'
});
},
someClickEvent: function() {
...
}
});

Is there a way to make a Marionette View listen for events on itself via the events hash?

I'm having trouble figuring out how to quickly, and simply attach a listener for events triggered on a Backbone.Marionette view.
I can currently accomplish what I'm looking for by adding a listener via .on, but is there a quick way via the events or triggers hashes? Something like this seems like it should work but doesn't:
return Marionette.ItemView.extend({
triggers: {
"click .close": "menu:close"
},
events: {
"menu:close #": "close",
},
close: {
// do stuff
}
}
Update
There is actually a (simple) way to do exactly what you want.
// Itemview
var itemView = Marionette.ItemView.extend({
initialize: function() {
Marionette.bindEntityEvents(this, this, this.events);
},
template: "#item",
triggers: {
"click .btn": "menu:performAction"
},
events: {
"menu:performAction": "performAction"
},
performAction: function() {
console.log('test');
}
});
In short this binds your events attribute containing the hashes to the views events.
Fiddle: http://jsfiddle.net/8T68P/
Documentation: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.functions.md#marionettebindentityevents
Old answer
See this fiddle: http://jsfiddle.net/Cardiff/K5TTQ/
Listening to events like that won't work indeed. And if you happen to use the .on method from within your view. Please use listenTo. That will be cleaned up properly when the view is closed. Like this:
// Itemview
var itemView = Marionette.ItemView.extend({
initialize: function() {
var view = this;
view.listenTo(view, "menu:performAction", view.performActionFromListenTo);
},
template: "#item",
triggers: {
"click .btn": "menu:performAction"
},
performActionFromListenTo: function() {
console.log('test');
}
});

Display a view using an existing rendered HTML with Backbone Marionette

I am having an application layout like the one attached. The upper panel is already to the page (i.e. in the server's HTML response). While the user interacts with the elements in that panel the content of the dynamic panel below changes accordingly.
I've studied Backbone Marionette various View types and Region Manager. But I still can't figure out a way to implement this. I need to capture events from the already rendered elements and change the dynamic content accordingly. As I understand, every time a region is created to show a specific Marionette view, the region's content is replaced by that view's el. And with that I cannot have a Layout view for the container of the whole thing.
So can this be done in anyway using Marionette?
You can certainly support what I would call a "pre rendered" or partial view. In fact, here's a Marionette View that I use quite a bit, as I'm working under with an app that includes server side partial views:
My.PartialView = Backbone.Marionette.Layout.extend({
render: function () {
//noop
if (this.onRender) {
this.onRender();
}
return this;
},
onShow: function () {
// make sure events are ready
this.delegateEvents();
}
});
It's simple to use:
My.NavBar = My.PartialView.extend({
events: {
"change #search-input": "searchRequested",
"click #faq-link": "faqRequested",
"click #home-link": "homeRequested",
},
searchRequested: function (e) {
// search
},
faqRequested: function (e) {
// show the faq
},
homeRequested:function () {
// go home
}
});
var navbar = new main.views.NavBar({ el: ".my-nav" });
someRegion.show();
// or, just wire up the events manually
navbar.delegateEvents();
I think the better way is using constructor.
Make your rendered layout class.
App.RenderedLayout = Marionette.Layout.extend({
render: function () {
if (this.onRender) {
this.onRender();
}
return this;
},
constructor: function(){
this._ensureElement();
this.bindUIElements();
Marionette.Layout.prototype.constructor.apply(this, slice(arguments));
}
});
Then you can use full of Marionette capabilities.
App.module('Some.Page', function (Mod, App, Backbone, Marionette, $, _) {
Mod.SomeLayout = App.RenderedLayout.extend({
el: '#renderedDiv',
events: {
'click .something': 'onSomethingClick'
},
regions: {
'innerRegion': '#innerRegion'
},
ui: {
something: '.something div'
},
initialize: function () {
},
onSomethingClick: function(e){
return false;
}
});
Mod.addInitializer(function(){
App.addRegions({renderedRegion: '#renderedDiv'});
Mod.someLayout = new Mod.SomeLayout();
App.renderedRegion.attachView(Mod.someLayout);
});
});

Right way for wiring backbone views

I have a two views:
1 LeftView (maximized when RightView is minimized & vice versa)
2 RightView (containing)
- collection of
- RightItemView (rendering RightItemModel)
When RightView is maximized and the user clicks a RightItemView, I want to maximize LeftView and display something according to the data from the clicked RightItemView.
What's the proper way to wire them?
I would recommend using the Backbone.Events module:
http://backbonejs.org/#Events
Basically, this line is all it takes to create your event dispatcher:
var dispatcher = _.clone(Backbone.Events);
Then all of your views can trigger/listen for events using the global dispatcher.
So, in RightItemView you would do something like this in the click event:
dispatcher.trigger('rightItemClick', data); // data is whatever you need the LeftView to know
Then, in LeftView's initialize function, you can listen for the event and call your relevant function:
dispatcher.on('rightItemClick', this.maximizeAndDisplayData);
Assuming your LeftView would have a function like so:
maximizeAndDisplayData: function(data) {
// do whatever you need to here
// data is what you passed with the event
}
The solution #jordanj77 mentioned is definitely one of the correct ways to achieve your requirement. Just out of curiosity, I thought of another way to achieve the same effect. Instead of using a separate EventDispatcher to communicate between the two views, why shouldn't we use the underlying model as our EventDispatcher? Let's try to think in those lines.
To start with, add a new boolean attribute to the RightItem model called current and default it to false. Whenever, the user selects the RightItemView, set the model's current attribute to true. This will trigger a change:current event on the model.
var RightItem = Backbone.Model.extend({
defaults: {
current: false,
}
});
var RightItemView = Backbone.View.extend({
events: {
'click li': 'changeCurrent'
}
changeCurrent: function() {
this.model.set('current', true);
}
});
On the other side, the LeftView will be handed a Backbone.Collection of RightItem models during creation time. You would anyways have this instance to supply the RightView isn't it? In its initialize method, the LeftView will listen for change:current event. When the event occurs, LeftView will change the current attribute of the model it is currently displaying to false and start displaying the new model that triggered this event.
var LeftView = Backbone.View.extend({
initialize: function() {
this.collection.on('change:current', this.render, this);
},
render: function(model) {
// Avoid events triggered when resetting model to false
if(model.get('current') === true) {
// Reset the currently displayed model
if (this.model) {
this.model.set('current') = false;
}
// Set the currently selected model to the view
this.model = model;
// Display the view for the current model
}
}
});
var leftView = new LeftView({
// Use the collection that you may have given the RightView anyways
collection: rightItemCollection
});
This way, we get to use the underlying model as the means of communication between the Left and Right Views instead of using an EventDispatcher to broker for us.
The solution given by #Ganeshji inspired me to make a live example
I've created 2 views for this.
var RightView = Backbone.View.extend({
el: $('.right_view'),
template: _.template('<p>Right View</p>'),
renderTemplate: function () {
this.$el.html('');
this.$el.append(this.template());
this.$link = this.$el.append('Item to view').children('#left_view_max');
},
events: {
'click #left_view_max' : 'maxLeftView'
},
maxLeftView: function () {
//triggering the event for the leftView
lView.trigger('displayDataInLeftView', this.$link.attr('title'));
},
initialize: function (options) {
this.renderTemplate();
}
});
var LeftView = Backbone.View.extend({
el: $('.left_view'),
template: _.template('<p>Left View</p>'),
renderTemplate: function () {
this.$el.html('');
this.$el.append(this.template());
},
displayDataInLeftView: function (data) {
this.$el.append('<p>' + data + '</p>');
},
initialize: function (options) {
//set the trigger callback
this.on('displayDataInLeftView', this.displayDataInLeftView, this);
this.renderTemplate();
}
});
var lView = new LeftView();
var rView = new RightView();
Hope this helps.

marionette simple event delegation

I am trying to add a simple event to the children under my compositeview but it is not triggering at all..and frankly I am not sure why, it seems so simple, I could do this just fine with normal backbone.view.
In the example below, the alert is not triggered at all, however when I purposefully change the function name the event binds to , to something else that doesnt exist, it complaints that the function doesnt exist, so I think it's something else...help?
App.View.ContentContainer = Backbone.Marionette.CollectionView.extend({
className:'content_container',
itemView:App.View.ContentBrowseItem,
events:{
'click .browse_item':'focus_content'
},
initialize:function () {
//this.views = {} //indexed by id
//this.create_modal_container()
var coll = this.collection
coll.calculate_size()
coll.sort_by('title', -1)
},
focus_content:function (e) {
alert('here???')
var $modal_container = this.$modal_container
var content_id = $(e.currentTarget).data('content-id')
var $selected_view = this.views[content_id]
var $focused_content = new App.View.FocusedItem({model:$selected_view.model})
$modal_container.empty().show().append($focused_content.el).reveal().bind('reveal:close', function () {
$focused_content.close()
})
return false
},
onShow:function(){
this.$el.addClass('content_container').isotope({
selector:'.content_item',
resizable:true,
layoutMode:'masonry',
masonry:{ columnWidth:64 }
})
}
EDIT: this is the resulting HTML: http://pastebin.com/uW2X8iPp the div.content_container is the resulting el of App.View.ContentContainer
Is .browse_item a selector for the App.View.ContentBrowseItem itemView element? In that case, you need to bind the event in the ItemView definition, not in the CollectionView definition. The reason is that events are bound when a view is rendered. The CollectionView itself is rendered before any of its child itemViews.
Also, if you are opening up another modal view on this click event, I would let the app handle that, rather than your CollectionView
Try something like this:
App.View.ContentBrowseItem = Backbone.Marionette.ItemView.extend({
...
initialize: function() {
// Maintain context on event handlers
_.bindAll(this, "selectItem")
},
events: {
"click" : "selectItem"
}
selectItem: function() {
App.vent.trigger("item:select", this.model);
}
...
});
And to actually show the modal detail view:
App.vent.on("item:select", function(itemModel) {
var detailView = new App.View.FocusedItem({ model: itemModel });
// You may also want to create a region for your modal container.
// It might simplify some of your `$modal_container.empty().show().append(..).etc().etc()
App.modalRegion.show(detailView);
});
Allowing each of your views to handle their own events is part of what makes Backbone and Marionette so beautiful. You'll just want to avoid one view getting all up in another view's business (eg. a CollectionView trying to handle its ItemView's events, an ItemView creating event bindings to show and close a separate modal view, etc.)
Hope this helps!

Resources