I need to extend marionette.js classes with some functionality I'd like to have in all classes I create in my app.
What I currently do is to save original method of Marionette and to override it with my own method, calling to original from inside overridden.
For instance:
(function() {
var oldMarionetteItemViewConstructor = Marionette.ItemView.prototype.constructor;
Marionette.ItemView.prototype.constructor = function() {
// Some custom stuff I want to have here
.....
// Call to original constructor
return oldMarionetteItemViewConstructor.call(this, arguments);
}
})();
It seems some hacky and I wonder if there better way?
Marionette hoists the Backbone.View.extend() method (which itself is actually hoisted from Underscore.js) so all you have to do is:
var MyFancyView = Marionette.ItemView.extend({
//define your custom stuff here
});
var MyExtendedView = MyFancyView.extend({
//This view picks up the same props/methods form MyFancyView
});
You're pattern works, but the native #extend() method will keep your prototypes clean:
https://github.com/jashkenas/underscore/blob/master/underscore.js#L838
Lets say I have the following Backbone view which loads two links, one with the anchor text "test1" and the other with the anchor text "test2".
I bind a click event and I get the HTML of the link that was clicked and store it inside the clickedHtml variable.
Now, this view is loaded by a Backbone router.
When the user clicks either one of the two links (test1 or test2) another view called "main" will be loaded by the router.
Now, how can I pass the "clickedHtml" variable to that view?
Should I use LocalStorage?
Should I declare it globally like window.clickedHtml?
Is there a better way?
Ty!
// file: views/test.js
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone) {
var Test = Backbone.View.extend({
el : '.test',
initialize : function () {
var that = this;
that.$el.html('test1<br />test2');
},
events : {
'click .test a' : 'click'
},
click : function (e) {
var clickedHtml = $(e.target).html();
}
return Test;
});
Here is my router:
// file: router.js
define([
'jquery',
'underscore',
'backbone',
'views/test',
'views/main'
], function ($, _, Backbone, Test, Main) {
var Router = Backbone.Router.extend({
routes: {
'' : 'home',
'test' : 'test'
}
});
var initialize = function () {
var router = new Router();
router.on('route:home', function () {
var main = new Main();
});
router.on('route:test', function () {
var test = new Test();
});
Backbone.history.start();
}
return {
initialize : initialize
}
});
Basicly you should use Backbone.Event:(Or it's equivalents in Marionette)
//Declaration
var notificationService = {};
_.extend(notificationService, Backbone.Events);
//Used by listener
notificationService.on("alert", function(o) {
alert(o);
});
//Used by publisher
notificationService.trigger("alert", {foo:"bar"});
The real question is how does it get passed from one view to another?
The way I see it, you have 2 options:
Bubble notificationService from one view to another in initialization
Wrap the notificationService with a requirejs model that returns it (creates a 'almost global' notificationService that can be passed by requirejs).
Although I don't like singletons a bit, this case a of a singleton notificationService object that can easily get injected by requirejs in every model will come in handy.
EDIT:
Another option, the quick and dirty one, just use jquery to trigger event on the DOM (specifically the body element) and listen to body in the other view
//on Listening view, after DOM is ready
$( "body" ).on( "alert", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
//on Triggering view, after DOM is ready
$( "body").trigger( "alert", [ "Custom", "Event" ] );
NOTE:
notice that once a listening view is closed, it must removes itself from listening to events (unbind/off), so you wont have memory leak
Architecturally speaking, your aim should be to keep your code generic & reusable.
One of the main things you don't want to do in a situation like this is to pass direct references from one object to another - if you end up changing the setup of one of the objects, or you need to pass data from another object as well, this can get messy really fast.
One design pattern that's widely used in situations like this is a mediator. Also known as "pub/sub" you can have a centralized standalone object that mediates information between objects. Certain objects will publish information and other objects can subscribe to them. The mediator acts as an intermediary so that the objects never have to communicate directly with each other. This makes a much more generic, reusable and maintainable solution.
More info here:
http://addyosmani.com/largescalejavascript/#mediatorpattern,
Javascript Patterns
On the Backbone side of things... If you've used Marionette, you may have come across a complimentary mini-library (also implemented by Derick Bailey) called wreqr. You can use this to create a simple mediator with low-overhead in your Backbone applications.
https://github.com/marionettejs/backbone.wreqr
It basically allows you to use backbone style events across objects. Example below:
First, you need to create a globally accessible mediator object, or add it to your app namespace or use require.js:
var mediator = new Wreqr.EventAggregator();
inside View #1
events : {
'click .test a' : 'click'
},
click : function (e) {
var clickedHtml = $(e.target).html();
// trigger an 'element:click' event, which can be listened to from other
// places in your application. pass var clickedHtml with the event
// (passed to the arguments in your eventhandler function).
mediator.trigger('element:click', clickedHtml);
}
Inside View #2
initialize: function(){
//...
this.listenTo(mediator, 'element:click', this.myEventHandler, this);
}
myEventHandler: function(elem){
// elem = clickedHtml, passed through the event aggregator
// do something with elem...
}
Backbone events are the way to go here.
When you capture the event in the view, I would bubble it up using:
click : function (e) {
var clickedHtml = $(e.target).html();
Backbone.Events.trigger("eventname",clickedHtml);
}
Then, you should be able to capture this in your router initialise function, using:
Backbone.Events.on("eventname", responseFunction); // listen out for this event
And then in the router declare a separate function:
responseFunction : function(clickedHtml)
{
//Do whatever you want here
}
I'm writing this from memory, so hopefully it make sense. I've also not tested catching an event like this i the router, but it should work.
HTH.
In the exact case you outline I would create a temp storage object on your global namespace and use that to transfer the data between your views, its a bit "hacky" but its better than using local storage, or the window object directly, at least with a temp object on your own global namespace the intent of the objects usage is known.
I find it better to use the http://backbonejs.org/#Events for a similar purpose of passing data between two views, though it does depend on how you structure your pages, if you have two views on the page representing a "control" or "component" this approach works really well.
If you post a link to your site or something I can have a look and give you some more help.
Russ
You could perhaps store it as a property on the view:
click : function (e) {
this.clickedHtml = $(e.target).html();
}
If your router can access both views, it can then simply pass the firstView.clickedHtml property to a function in the secondView (or to the initializer)
I have a backbone marionette view in which i have defined many events.
I want to store a log for any event which is occuring inside my itemview. I dont want to write function calling for my audit data on every data, instead i had like to override backbone marionette events method so that it is applied on all my ItemViews.
I tried using:
var originalTrigger = Backbone.Events.trigger;
Backbone.Events.trigger = function(){
console.log("Event Triggered:");
console.log(arguments.join(", "));
originalTrigger.apply(this, arguments);
}
But it doesnt do anything for me. Please help
Thank you in advance
If you check the Backbone source you'll see things like this:
_.extend(Model.prototype, Events, {
where Model and Events are local aliases for Backbone.Model and Backbone.Events respectively. That means that the methods from Backbone.Events will have been copied to the model, collection, and view prototypes before you have a chance to wrap Backbone.Events.trigger with your auditing.
You'll want to wrap all four triggers after Backbone is loaded but before anything else (including Marionette) is loaded. Something like this:
(function() {
var trigger = Backbone.Events.trigger;
var wrapper = function() {
console.log("Event Triggered:");
console.log(arguments.join(", "));
trigger.apply(this, arguments);
};
Backbone.Model.prototype.trigger = wrapper;
Backbone.Collection.prototype.trigger = wrapper;
Backbone.View.prototype.trigger = wrapper;
})();
after <script src="backbone.js"> but before <script src="backbone.marionette.js"> should do the trick.
I am reading through BackboneJS View .
SearchView = Backbone.View.extend({
initialize: function(){
alert("Alerts suck.");
}
});
// The initialize function is always called when instantiating a Backbone View.
// Consider it the constructor of the class.
var search_view = new SearchView();
Is every function inside a View object called on instantiation or is it only the initialize function alone??
Is initialize more like a callback function on success of instantiating a view? what exactly is it meant for?
I went through google. But found most results having buzz words that i couldn't understand. can someone put it straight away simple? assuming I have no knowledge about underscorejs?
Only the initialize function is called on instantiation. You can regard it as a constructor of sorts.
Even in the documentation, the title of the initialize function is constructor/initialize.
... If the view defines an initialize function, it will be called when the view is first created.
It would make no sense at all if every function was called on instantiation. Imagine a case where you have some destructive logic in one of the functions of your class (which is very likely), you wouldn't want that function called right away.
Any other functions that you want to execute the moment the object is instantiated can simply be called from within the initialize function.
initialize: function(){
// alert("Alerts are not too cool (no offence).");
console.log( "Consoles are cool" );
another_init_func();
more_init_stuff();
be_awesome();
...
}
I'm creating a Backbone.js plugin that offers a basic grid layout given supplied JSON data. My problem is that I'm not sure how to deal with binding events to a View class without altering the plugin itself. And I'd rather not do this -- I'd rather have the user of the plugin be able to extend the view, or alter its prototype to bind custom events.
The View in the plugin is a basic view without any events binded. It also contains some other functions which I've omitted for simplicity.
FlipCard.CardView = Backbone.View.extend({
tagName: 'div',
className: 'card',
// and more
});
I've attempted to use the prototype attribute in my separate app.js file to bind events, but they don't seem to be triggered.
FlipCard.CardView.prototype.events = {
'click .card' : 'alert'
};
FlipCard.CardView.prototype.alert = function(){
alert("hello!");
};
And I'm familiar with the .extend({}) function, but that won't work unless I can somehow inform the plugin to use the extended version of the view... which I'd rather not do.
Any ideas on what I should be doing here?
EDIT: Turns out it was a silly error. Because the view has the class '.card' and I was trying to bind a click event to '.card', it's unnecessary to put in 'click .card'. Instead the event should be:
FlipCard.CardView.prototype.events = {
'click' : 'alert'
};
If someone were to use their plugin, they would extend your FlipCard.CardView in the same way you are extending Backbone.Model
myApp.Views.myCardView = FlipCard.CardView.extend({
events: {
'click .card' : 'alert'
},
alert: function() {
alert("hello!");
}
}
This creates an extended version of your plugin view with events bound to it, and it does not alter the plugin in any way. The user would then instantiate it as normal:
var someView = new myApp.Views.myCardView();