Backbone.View.remove in a Marionette application - marionette

To destroy a Backbone view, you would call its remove method, but in a Marionette application, the views provide a new destroy method which does the same, but also takes care of removing child views. Does this mean the remove method should never be used on Marionette views?

Looking at the source, we can see that Marionette view destroy() method internally calls Backbone remove() method. Calling remove() will delete the dom element and unbind events, but Marionette destroy() is more powerful and does a lot more plumbing, like destroying behaviors and etc. So in Marionette apps you should only use destroy().
destroy: function() {
if (this.isDestroyed) { return this; }
var args = _.toArray(arguments);
this.triggerMethod.apply(this, ['before:destroy'].concat(args));
// mark as destroyed before doing the actual destroy, to
// prevent infinite loops within "destroy" event handlers
// that are trying to destroy other views
this.isDestroyed = true;
this.triggerMethod.apply(this, ['destroy'].concat(args));
// unbind UI elements
this.unbindUIElements();
this.isRendered = false;
// remove the view from the DOM
this.remove();
// Call destroy on each behavior after
// destroying the view.
// This unbinds event listeners
// that behaviors have registered for.
_.invoke(this._behaviors, 'destroy', args);
return this;
},

Related

How to Include events (not event-plugin) in Ractive initialization/defaults?

I've read through the Ractive Documentation and I'm scratching my head a bit, because it seems like the default events initialization option allows me to do something - create new eventtypes - far more complex than what i need but conversely, there's no hook for the simpler, (more common?) task of defining default events
Could someone advise on how to provide global events that could be fired for traditional DOM events?
Example:
I have a 3 Component application page. I want to define a getOptions event, such that any <select on-click='getOptions'>...</select> will be handled by the same function. I don't want to have to define that function in each component.
My intuition would have been to do the following:
Ractive.events['getOptions'] = function(event){
//logic for getting the options for the value in event.keypath
}
or, if i wanted a true default that could be overridden...
Ractive.default.events['getOptions'] = function(event){
//logic for getting the options for the value in event.keypath
}
but my understanding of the documentation, is that Ractive.events and Ractive.default.events do not provide this, but rather provide a way to define new event plugins, that depend on a separate mechanism for getting fired:
Ractive.events.getoptions = function(node,fire){
//here goes logic for interacting with DOM event listeners, etc
}
//and then i would need to do this
ractive = Ractive.extend({...});
ractive.on('someOtherEventName',function(event){
//logic for getting the options for the value in event.keypath
});
//and then I could do this...
<select on-getoptions='someOtherEventName'>...</select>
but what would fire the getoptions in this case - from the template, rather than js ractive.fire()?
Would something like <select on-getoptions='someOtherFunction' on-click=getoptions>...</select> work? That seems very strange to me. Do I understand the concept correction? If not, what am i missing?
Is there a simple way to achieve the first example?
Ractive.events refers to custom events for mediating between the dom and the template:
Ractive.events.banana = function( node, fire ) { ... };
<div on-banana="doSomething()"/>
The handler for the event can either be the name of an event to fire, or a method on the component instance.
In your case, I think defining a method on the Ractive.prototype would be the best way to have a common handler:
Ractive.prototype.getOptions = function( /* pass in arguments */ ){
// and/or this.event will give you access
// to current event and thus context
// you can also override this method in components and
// call this base method using this._super(..)
}
// now any ractive instance can use:
<select on-click="getOptions(data)">...</select>
An event based approach usually entails letting the root instance or common parent in the view hierarchy handle same event across child components:
var app = new Ractive({
template: "<componentA/><componentB/>",
oninit(){
this.on( '*.getOptions', ( event, arg ) => {
// any child component (at any depth)
// that fires a "getOptions" event will
// end up here
});
}
});
// in component A or B:
<select on-click="getOptions">...</select>
UPDATE: If you wanted to assign an event handler to the prototype, so in essence every component is pre-wired to handle an event of a set name, you could do:
Ractive.prototype.oninit = function(){
this.on( 'getOptions', ( event ) => {
// handle any "getOptions" event that happens in the instance
});
}
Just be aware that you must call this._super(); in any component in which you also implement oninit:
var Component = Ractive.extend({
oninit() {
// make sure we call the base or event listener won't happen!
this._super();
// do this component instances init work...
}
}

Backbone: Attaching event to this.$el and re rendering causes multiple events to be bound

I need to attach an event to the main view element, this.$el. In this case its an 'LI'. Then I need to re render this view sometimes. The problem is if i re render it, it attaches any events in the onRender method that is attached to this.$el each time its rendered. So if i call this.render() 3 times the handler gets attached 3 times. However, if i attach the event to a childNode of this.$el, this does not happen and the events seem to be automatically undelegated and added back on each render. The problem is I NEED to use the main this.$el element in this case.
Is this a bug? Shouldn't this.$el function like the childNodes? Should I not be attaching things to this.$el?
inside the view:
onRender: function(){
this.$el.on('click', function(){
// do something
});
If you're able to use the view's event hash, you could do the following:
var Bookmark = Backbone.View.extend({
events: {
'click': function() {
console.log('bound once')
}
}
...});
If for some reason that's not an option, you could explicitly remove any existing event listeners for this event in the render method, which will prevent the listener from being attached multiple times:
var Bookmark = Backbone.View.extend({
...
render: function(x) {
this.$el.off('click.render-click');
this.$el.html(this.template());
this.$el.on('click.render-click', function () {
console.log('only ever bound once');
});
return this;
}
});

How to inspect bindings on a Marionette view?

Is there a way to examine active bindings on a Marionette view?
The bindings are created in the controller as follows:
// controllers/custom_controller.js
this.customView.bind("some:custom:event", this.customEventHandler, this);
The custom event is triggered within the view:
// views/custom_view.js
onSomething: function() {
this.trigger("some:custom:event");
}
I would like to check whether this.customView has a event handler for some:custom:event.
this.customView._events is an object of the bound events. So to check if the event exists:
if (this.customView._events["some:custom:event"]) {
//do something
}

How do I add default events to Marionette's Marionette.View base type?

I am currently extending Marionette's base Marionette.View type with the method I named quickClick. I'm doing this to
config/marionette/view.js
(function() {
define([
'backbone.marionette'
],
function(Marionette){
return _.extend(Backbone.Marionette.View.prototype, {
quickClick: function(e) {
$(e.target).get(0).click();
}
});
});
}).call(this);
This allows me to call this method from any view I create without having to redefine it per view. Great!
Here's a trimmed down view with the events object still in place:
(function() {
define([
'backbone.marionette',
'app',
'templates'
],
function(Marionette, App, templates){
// Define our Sub Module under App
var List = App.module("SomeApp");
List.Lessons = Backbone.Marionette.ItemView.extend({
events: {
'tap .section-container p.title': 'quickClick'
}
});
// Return the module
return List;
});
}).call(this);
In case your wondering, tap is an event I'm using from Hammer.js because this is a mobile app. So, in order to circumvent the 300ms click event delay on iOS and Android, I'm manually triggering a click event when the tap event fires on certain elements.
Now, all of this is working just fine, and I felt it was necessary to describe this in detail, so that an answer could be given with context.
My problem is having to define the events object. I don't mind at all for elements as specific as the one above, .section-container p.title. But, I would like to register a tap event for all <a> tags within every view. It doesn't make sense to keep defining this event in each view I create
events: {
'tap .section-container p.title': 'quickClick',
// I don't want to add this to every single view manually
'tap a': 'quickClick'
}
Instead, of adding this to every view, I thought I would just add an events object to the config/marionette/view.js file where I added a method to the Marionette.View prototype.
Here's what I did
(function() {
define([
'backbone.marionette'
],
function(Marionette){
return _.extend(Backbone.Marionette.View.prototype, {
events: {
'tap a': 'quickClick'
},
quickClick: function(e) {
$(e.target).get(0).click();
}
});
});
}).call(this);
Of course, that doesn't work. The events object is overridden each time I need to add events that only apply to that view. Btw, tap a does work when my view does not have its' own events object.
So, my question is: How do I add default events to Marionette's Marionette.View base type?
"Of course, that doesn't work. The events object is overridden each time I need to add events that only apply to that view."
Yes, that seems to be the problem. Here is the part of Marionette that does the event delegation:
// internal method to delegate DOM events and triggers
_delegateDOMEvents: function(events){
events = events || this.events;
if (_.isFunction(events)){ events = events.call(this); }
var combinedEvents = {};
var triggers = this.configureTriggers();
_.extend(combinedEvents, events, triggers);
Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
},
One possible solution could be overwriting this (private!) part of Marionette - but it could probably change in new versions of Marionette and you'd always have to make sure that things still work. So this is bad.
But you could do something like this in your subviews.:
events: _.extend(this.prototype.events, {
'tap .section-container p.title': 'quickClick'
})
If this makes sense for only one 'global' event is another question.
Or you could define an abstract View Class, which does something like that
events: _.extend({'tap a': 'quickClick'}, this.my_fancy_events)
and also defines the quickClick method and then use this view for all you subviews. They then define their events not in 'events' but in 'my_fancy_events'.
When extending the views I occasionally find myself in situation when I need to add some extra calls in 'initialize' as well as extend 'events' property to include some new calls.
In my abstract view I have a function:
inheritInit: function(args) {
this.constructor.__super__.initialize.apply(this, args);
this.events = _.extend(this.constructor.__super__.events, this.eventsafter);
},
Then, in an extended view, I can call
initialize: function(options) {
this.inheritInit(arguments)
//..some extra declarations...
}
and also I can use 'events' property in a regular way.

Backbone.js - event trigger not work after rendering other views

There's a addPost function in my router. I don't want to re-create the postAddView every time the function is invoked:
addPost: function () {
var that = this;
if (!this.postAddView) {
this.postAddView = new PostAddView({
model: new Post()
});
this.postAddView.on('back', function () {
that.navigate('#/post/list', { trigger: true });
});
}
this.elms['page-content'].html(this.postAddView.render().el);
}
Here's the PostAddView:
PostAddView = backbone.View.extend({
events: {
'click #post-add-back': 'back'
}
, back: function (e) {
e.preventDefault();
this.trigger('back');
}
});
The first time the postAddView is rendered, the event trigger works well. However, after rendering other views to page-content and render postAddView back, the event trigger won't be trigger anymore. The following version of addPost works well, though.
addPost: function () {
var that = this, view;
view = new PostAddView({
model: new Post()
});
this.elms['page-content'].html(view.render().el);
view.on('back', function () {
delete view;
that.navigate('#/post/list', { trigger: true });
});
}
Somewhere you are calling jQuery's remove and that
In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
so the delegate call that Backbone uses to bind events to your postAddView.el will be lost. Then, when you re-add your postAddView.el, there are is no delegate attached anymore and no events are triggered. Note that Backbone.View's standard remove method calls jQuery's remove; a few other things in jQuery, just as empty will do similar things to event handlers. So the actual function call that is killing your delegate could be hidden deep inside something else.
You could try calling delegateEvents manually:
this.elms['page-content'].html(this.postAddView.render().el);
this.postAddView.delegateEvents();
or better, just throw the view away and create a new one every time you need it. Your view objects should be pretty light weight so creating new ones should be cheap and a lot less hassle than trying to keep track of the existing views by hand.
If you really want to reuse the current DOM and View you do not need to set again and again the element as you are doing, everything that you call .html() you are destroying the DOM of the View and generating again and losing events. Also I prefer always to add the "el" in the DOM before render the View. I will have your function in this way:
addPost: function () {
if (!this.postAddView) {
this.postAddView = new PostAddView({
model: new Post()
});
this.postAddView.on('back', this.onBack);
this.elms['page-content'].html(this.postAddView.el);
}
this.postAddView.render();
},
onBack : function () {
this.navigate('#/post/list', { trigger: true });
}
I'm not fan of the use of local variables to refer to "this". If all of your Views uses _.bindAll(this) in the initialize method you could bind your events to your view and could use this(check how I transformed onBack).
With my code there is not a need to manually call this.delegateEvents()

Resources