Passing data from one Backbone view to another - javascript

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)

Related

Backbone.js and refactoring correctly

I'm new to backbone so forgive me if this is obvious. I wrote a function to change the value associated with a toggle switch to either true or false based on its position. I used this code in two different views and want to refactor it out.
I created a Utils object and attached the function as a method to that object. I then imported Utils into both views. Here is a bit of the code as I have it properly functioning now:
var AddView = AbstractView.extend({
template: "path/to/template.html",
events: {
"change .toggleBoolean" : "temp"
},
temp: function(e){
Utils.toggleValue.call(this, e);
}, ...
This works in both places as expected. However, I was hoping to replace "temp" in the events hash with the temp method. Any direction on how to properly do this would be greatly appreciated.
You can simply do this:
var AddView = AbstractView.extend({
template: "path/to/template.html",
events: {
"change .toggleBoolean" : Utils.toggleValue
},
Utils.toggleValue will be invoked in view's context.
Here is the part of backbone code that deals with the event object:
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[method];
if (!method) continue;
var match = key.match(delegateEventSplitter);
this.delegate(match[1], match[2], _.bind(method, this));
//-------------------------------------^ context is handled here
}
it checks whether value is a function, and binds the handler function context to view
You could just use a reference instead of a string
var Myview = Backbone.View.extend({
events: {
'click p': Utils.action
},
});
plnkr
Or if you want to mix the util methods into the view class instead of relying on delegation you can do
var Myview = Backbone.View.extend({
events: {
'click p': 'action'
},
});
Myview.prototype.action = Utils.action;
plnkr
The above will preserve the context as you can see in the plunker.
My preferred method if you plan to start pulling more logic out this way would be to look at a plugin that offers mixin functionality. Marionette has (amongst many other useful things) functionality for sharing behaviors between views. There are several other approaches as well that you can research by googling for "Backbone mixin".

Unit testing Backbone.Marionette listeners

I'd like to check what listeners are attached to my Marionette component, for example to the controller:
Example code of the component:
var MyController = Marionette.Controller.extend({
initialize: function () {
this.listenTo(OtherModule, "start", function () {
// something happens here
});
this.listenTo(OtherModule, "stop", function () {
// something happens here
});
})
});
var myController = new MyController();
Example code of the unit test:
describe("MyController", function () {
it("should have 2 listeners registered", function () {
// ?
});
});
I can trigger the events and see if the function I wanted to use was executed with the use of the jasmine's spyOn method, but I'm curious if there's a list of attached events available directly on the component.
How can I check what is my component listening to?
I think you're approaching unit testing in the wrong way - unit tests should check that your object interacts with the outside world in the expected way. They shouldn't be concerned with implementation details (like the exact number of event listeners an Object has).
Having said that, you can use the _listeners (Backbone 1.0.x) or _listeningTo (Backbone 1.1.x) property:
var controller = new MyController;
describe("MyController", function () {
it("should have 2 listeners registered", function () {
expect(Object.keys(controller._listeners).length).toEqual(2)
});
});
Source - Marionette.Controller extends Backbone.Events, which stores listeners in that property.
I wouldn't use this approach in a unit test, but it can be very useful for debugging memory leaks.
When I want to debug this kind of thing I often use a window.MyController = MyController. Then in the console I can save window.MyController and play around with it.
It looks like it will show the objects it's listeningTo but I'm not necessarily seeing what events it's tied to in this fashion. Anyway might be a look see. I'm also using Chrome so Firebug in Mozilla might give better info.

Eventbus/Aggregator for two Requirejs apps

I have two applications (more to be added that may or may not use backbone + requirejs), both developed using backbone + requirejs. I want to create an eventbus on which both applications can publish and subscribe to specific events. I have considered a two options, both of which have their own inefficiencies. These include:
Using the document object since this is common to all applications on the page regardless of framework/architecture e.g.:
// Aggregator
define([], function () {
var eventAgg = document.getElementsByTagName('body')[0],
slice = Array.prototype.slice;
function _on() {
var args = slice.call(arguments);
eventAgg.addEventListener(arg[0], arg[1]);
}
function _trigger() {
var args = slice.call(arguments);
eventAgg.dispatchEvent(arg[0]);
}
return {
on: _on,
trigger: _trigger
};
});
// Somewhere in one of app 1's modules
define(['jquery',
'underscore',
'backbone',
'dispatch',
'someView'], function ($, _, Backbone, Dispatch, SomeView) {
...
Dispatch.on('init', function (e) {...};);
...
});
// Somewhere in one of app 2's modules
...
var customEvent = new CustomEvent('init', {'status': 'All data loaded successfully'});
dispatcher.dispatchEvent(event);
...
Extending Backbone.Events and injecting the event aggregator into all requirejs modules (though this approach has been finicky at best). Same approach as above except I extend Backbone.Events instead of using the document object.
Neither of these methods seem 'correct' for providing an global event aggregator but I have not been able to come up with anything better. Any suggestions?
Backbone is itself, an event bus. Which is probably the most straight forward way of doing it.
Backbone.on('myevent:app1', function(){alert('sup');})
Backbone.trigger('myevent:app1');

What is the proper way to update main class in javascript with jquery events?

Assuming I have something like:
var MyApp = function() {
this.name = "Stacy"
}
MyApp.prototype.updateName = function(newname) {
this.name = newname;
}
In my main page I have a :
$(function () {
var instance = new MyApp();
})
I have a button event handler that would update the name:
$("#button").on("click", function(evt) {
// Update the name in MyApp to something else...
instance.name = "john" // I do not like using instance here, because it has to be "instance" has to be created before I can use it. I want to be able to make this independent of "instance" being created or not
});
What is the proper way to do it such that the button handler would update "MyApp" to have the correct name, without explicitly using the created "instance" of myapp as part of the button's click handler?
ideally I would like to shove that jquery event handler somewhere into "MyApp" such that I could do something like:
MyApp.prototype.events = function() {
$("#button").on("click", function(evt) {
this.name = "john"
});
}
Though it doesnt work because this refers to something else.
How to properly structure my application such that the event handler is more or less updating the properties of the "MyApp" so that it can be independent of the created "instance" (i.e. i no longer have to use the "instance.")?
First, if you create an setter function, it's a good idea to use it !! :D
$("#button").on("click", function(evt) {
// Update the name in MyApp to something else...
//instance.name = "john"
instance.updateName("john");
});
And then, it does not make sense to do put an event handler inside of a method of your object MyApp, since it will never bind the onclick event until you fire events()
Then... my way to organize this, is to use the jQuery document onload to bind all the DOM objects with the function of your applications. Usually something like this:
MYAPP = {};
MYAPP.say_something = function () {
alert('lol, you clicked me!');
};
...
$(function () {
$('#my_button').click(MYAPP.say_something);
$('#other_element').mouseenter(MYAPP.another_method);
});
And for big applications, where you have to work with a lot of elements, you can organize your code much better if you have a namespace for your DOM elements, something like this:
MYAPP.fetch_dom = function () {
return {
my_button: $('#my_button'),
other_element: $('#other_element')
};
};
And you can bind the events in a very neat way
$(function () {
// first initiate DOM
my_dom = MYAPP.fetch_dom();
// Then bind events
my_dom.my_button.click(MYAPP.say_something);
my_dom.other_element.mouseenter(MYAPP.another_method);
});
This way you don't have to look for the specific elements in the DOM from a thousand points of your programme, spreading hardcoded id's everywhere and performing noneffective searches against the DOM structure.
Finally, it is much better to use literals in JS rather than using the word new. JS is a prototypical OOP language and new is a little bit "against nature" that can be a pain in the ass.

What is the advantage of custom events in backbone?

I understand how custom events work in Backbone and how to trigger them, but I'm having trouble understanding when exactly to use them and what purpose they serve over just calling the function directly.
e.g.
var MyView = Backbone.View.extend({
tagName: 'div',
className: 'myview',
initialize: function() {
this.model.on("mycustomevent", this.doSomething, this);
},
doSomething: function() {
console.log('you triggered a custom event');
}
});
If I am not mistaken, The doSomething method can be called by using this.model.trigger("mycustomevent") within other methods, but can be also called directly with this.doSomething()
Outside the view, it can be called similarly with
var myview = new MyView({model:somemodel});
myview.model.trigger("customevent");
myview.doSomething();
What I am confused about is why not forgo the the custom event and just call the method directly when you need it? Any example uses would be greatly appreciated!
You might want to add multiple handlers in different places in the code, f.ex:
this.model.on("mycustomevent", this.doSomething, this);
// ... and somewhere else you add an anonymous function
this.model.on("mycustomevent", function() {
console.log('do something');
});
Then when you trigger the event, it will execute all handlers. You can also use off to unbind/manage individual or multiple handlers.
If you are asking about a generic explanation of the event pattern (also called observer pattern, publish/subscribe, etc...), you should probably look for a more in-depth article or book.
With backbone, the perfect example is changing a property of a model. Using a function, you would have to do something like this...
$( '#someUI' ).click( function {
// update the model property
myModel.someProperty = 'somethingDifferent';
// update any ui that depends on this properties value
$( '#uiThatDisplaysModelData' ).find( 'someSelector' ).html( 'somethingDifferent' );
// save the model change to the server
$.ajax( {
url: 'somesaveurl',
data: { someProperty: 'somethingDifferent' }
success: callback
} );
} );
And then repeat those steps all over your code for each property change.
With backbone and a little setup the same things can be accomplished with:
myModel.set( 'property', 'somethingDifferent' );
This is because we have attached handlers to the change and change:property events of this model. These are custom events that are created automatically for models by backbone. So whenever any part of your code manipulates the model, the DOM updates and saving can be done automatically. We can also bind input validation or whatever we want to these custom events.
It's basically just applying the observer pattern to your application, where events belong to an object that is observable, and the handlers belong to its observers.
http://en.wikipedia.org/wiki/Observer_pattern

Categories

Resources