Is there a preferred way to trigger Router.navigate in Backbone when a user clicks a link?
For instance a template might have a link Log Out. Is the preferred approach really to use a custom class and attach a click handler to that class in the view? This seems to generate tons of duplicate code so I'm looking for a better way.
The way to handle this kind of thing is to extend the Backbone objects ( in this case the View). You'll notice in the Backbone docs that this is encouraged, and necessary given its minimalist code base. I'd recommend checking out Marionette (on Github) and the site Backbone patterns for good ways to extend the Backbone core.
For example, maybe you extend View with a method that wires up the navigation handlers as you like:
Backbone.View.prototype.wireupNavs = function() {
var that = this;
this.$el.find("a[role=nav]").each(function() {
var target = $(this).attr('href');
that.bind("click", router.navigate(target);
});
}
Then any a tag you want as a Backbone nav element, you'd just decorate with the role="nav" attribute; and call this.wireupNavs() in the initializer function of the appropriate views.
Related
I've inherited a codebase that follows the format of: a router sets a controller, the controller fetches the collection/model needed, then the controller set/passes the view the collection/model.
The current View I'm working on loads a collection, and now I need to build in a feature where I fetch a single model after the view has rendered, based on an id clicked (note the model is from a different collection).
I only want to load the model when/if they click a button. So my question is, can I setup the model/fetch in the View, or should I be doing that in the controller? Is there a backbone best practice when adopting a controller/view setup like this?
I primarily ask because it seems easier for me to add this new feature right in the View. But is that a bad practice? I thought so, so I started down the path of triggering an event in the View for the controller to the fetch the model, and then somehow pass that back to the View (but I'm not sure really how to even do that)...it seems like a lot of unnecessary hoop jumping?
Its OK to fetch collection via views. As 'plain' backbone does not Controller, View in charge of it responsibilities.
But imho fetch collections via controller is better practice, its easier to scale and support and test.
The only difficulty is to set communication between Controller and View context event. One of the approach is trigger Message Bus event on context event like
events: {
'click .some': function() {
this.trigger('someHappend', { some: data })
}
}
and listen to this event in Controller
this.on(someViewInstance, 'someHappend', function() {
// do something in controller
})
If you already inherited code with structure you described you'd better follow it. Also you might be interested in MarionetteJS as significant improvement. Also highly recommend you to checkout BackboneRails, screencasts not free but very usefull, especially in large scale app maintain
Many of the views in my application need to be "collapsible". To the user this means that you can click an arrow to collapse or expand the view's contents.
When creating a view I need to be able to easily say, "This view should be collapsible," and then run the appropriate setup code (which essentially means adding the .collapsible class to the view's wrapper and inserting a dom element that looks like this: <div class="toggle"></div>
Suggestions on ways to pull this off seamlessly? I'm currently using Backbone, Backbone.Marionette, and Underscore.
I do this with another application that doesn't use Backbone. In that application every action results in a page refresh, so I just use jQuery to look for all elements with the .collapsible class and do my setup that way.
EDIT:
I'm using Backbone.Marionette.CompositeView for these particular views, if that helps.
I've done similar thing in my project by extracting such functionality into mixins. There're different approaches to implementing mixins in Backbone. Take a look here or here
You can create parent view that extends from Marionettes compositeView and add your common functionallity there, and have your project views extend from this parent view.
var CollapsibleView = Backbone.Marionette.CompositeView.extends({
variable1: 1,
var2: true,
initialize : function() {
// your code here
},
helperfunction : function () {
// other helpful function
}
});
var MySpecificView = CollapsibleView.extends({
mySpecificFunction : function () {
// some specificView functionality
}
});
var myProjectView= new MySpecifcView();
myProjectView.helperfunction(); /// function from the parent
myProjectView.mySpecificFunction(); /// function from the specificView
/// you also have the functionality added on the initialization of the collpasibleView
I am trying to test drive a view event using Jasmine and the problem is probably best explained via code.
The view looks like:
App.testView = Backbone.View.extend({
events: { 'click .overlay': 'myEvent' },
myEvent: function(e) {
console.log('hello world')
}
The test looks something like:
describe('myEvent', function() {
it('should do something', function() {
var view = new App.testView();
view.myEvent();
// assertion will follow
});
});
The problem is that the view.myEvent method is never called (nothing logs to the console). I was trying to avoid triggering from the DOM. Has anyone had similar problems?
(Like I commented in the question, your code looks fine and should work. Your problem is not in the code you posted. If you can expand your code samples and give more info, we can take another look at it. What follows is more general advice on testing Backbone views.)
Calling the event handler function like you do is a legitimate testing strategy, but it has a couple of shortcomings.
It doesn't test that the events are wired up correctly. What you're testing is that the callback does what it's supposed to, but it doesn't test that the action is actually triggered when your user interacts with the page.
If your event handler needs to reference the event argument or the test will not work.
I prefer to test my views all the way from the event:
var view = new View().render();
view.$('.overlay').click();
expect(...).toEqual(...);
Like you said, it's generally not advisable to manipulate DOM in your tests, so this way of testing views requires that view.render does not attach anything to the DOM.
The best way to achieve this is leave the DOM manipulation to the code that's responsible for initializing the view. If you don't set an el property to the view (either in the View.extend definition or in the view constructor), Backbone will create a new, detached DOM node as view.el. This element works just like an attached node - you can manipulate its contents and trigger events on it.
So instead of...
View.extend({el: '#container'});
...or...
new View({el:'#container'});
...you should initialize your views as follows:
var view = new View();
$("#container").html(view.render().el);
Defining your views like this has multiple benefits:
Enables testing views fully without attaching them to DOM.
The views become reusable, you can create multiple instances and render them to different elements.
If your render method does some complicated DOM manipulation, it's faster to perform it on an detached node.
From a responsibility point of view you could argue that a view shouldn't know where it's placed, in the same way a model should not know what collection it should be added to. This enforces better design of view composition.
IMHO, this view rendering pattern is a general best practice, not just a testing-related special case.
Trying to create a page that allows users to add edit and view a parent child combined.
UI has 3 columns
Parent : List of Parents Children : Child
I want to configure the controllers(s) so that users can come back to right where they were but see no need to have it so both Parent and child can be editable.
// Getting closer using backbone marionette but still having some small issues
MyRouter = Backbone.Marionette.AppRouter.extend({
appRoutes: {
'': 'AddClient',
'View/:clientid': 'ViewClient',
'Edit/:clientid': 'EditClient',
'View/:clientid/Add': 'PolicyAdd',
'View/:clientid/View/:policyid': 'PolicyView',
'View/:clientid/Edit/:policyid': 'PolicyEdit'
}
});
someController = {
AddClient: function () {
var someView = new ClientAdd();
MyApp.clientPane.show(someView);
},
ViewClient: function (clientid) {
var someView = new ClientView();
MyApp.clientPane.show(someView);
},
EditClient: function (clientid) {
var someView = new ClientEdit();
MyApp.clientPane.show(someView);
},
PolicyAdd: function (clientid) {
this.ViewClient(clientid);
var someView = new PolicyAdd();
MyApp.policyPane.show(someView);
},
PolicyView: function (clientid, policyid) {
this.ViewClient(clientid);
var someView = new PolicyView();
MyApp.policyPane.show(someView);
},
PolicyEdit: function (clientid, policyid) {
this.ViewClient(clientid);
var someView = new PolicyEdit();
MyApp.policyPane.show(someView);
}
};
Having the "this.ViewClient" feels hacky and also doesn't work.
Multi-part answer, here...
"this.ViewClient is not a function"
this is a bug in Marionette. the controller method is called in the context of the router instead of the controller, so the call to this.ViewClient is trying to find it on the router.
oops.
bug logged. will fix asap. https://github.com/derickbailey/backbone.marionette/issues/38
--
UPDATE: this bug is now fixed in v0.5.1 of Backbone.Marionette https://github.com/derickbailey/backbone.marionette
--
to work around this issue for now, you can do this:
PolicyEdit: {
someController.ViewClient();
// ...
}
If that doesn't work, you may need to use Underscore.js' bind or bindAll methods to ensure the correct binding on your controller functions.
These workaround won't be necessary once i get the bug fixed... hopefully later today / tonight.
is basically calling other routes the best way to manipulate multiple regions?
The direct answer to this question is no.
But, you're not calling a route in this case. You're calling a method on your controller. That's perfectly fine - and actually, I would encourage this. It's a proper use of your object, and is one of the things that I think should be done instead of calling another route / router handler.
Routers And Controllers
A router is a feature, not an architectural requirement. Your app should work without a router, and a router should only add the ability to use bookmarks and the browser's forward/backward button.
With that philosophy in mind (which I know is controversial), using a controller like you have and calling multiple methods on your controller in order to get your application to the correct state, is one of the right approaches to take.
Look at it this way: if you removed the router from your app, you would be forced to call methods on your controller directly. To prevent duplication of code, you'll want to create many small methods on your controller that can do one thing very well, and then compose larger methods out of those smaller methods.
Hope that helps. :)
What is the best way to bind events to a Backbone boilerplate application? I've been trying to bind my events directly to the models associated with my views, in my views, but it doesn't seem to be working. I see within 'namespace.js', that there is an app key that extends Backbone.Events like so:
// Keep active application instances namespaced under an app object.
app: _.extend({}, Backbone.Events)
I don't fully understand how to use it...
I was able to get things working without the boilerplate, but it does provide some very cool functionality, so I'd love to be able to use it. Thanks!
ADDED
the code I was using was with the underscore bind method like so:
this.module.bind('change', this.render);
But then, I realized that 'this.model' is returning undefined, and so this doesn't work. I really am not sure how the boilerplate wants me to reference my model from the view.
I'm not sure if it is a typo that you copied from your code or a typo you only entered here, but I believe this.module (which IS undefined) should be this.model, which you also must be sure to pass in when you instantiate your view, of course, as so:
myView = new BBView({model: myModel});
then you can say this.model.bind('change', this.render); or this.model.on('change', this.render); for the most recent version of Backbone
I frequently bind my views to change events on my models in this way.
As for extending Backbone.Events, the way I have used it is to create an independent "event aggregator" that will help connect events between different views on your page. Let's say for example you have some action on one view that needs to set off an action on another view. In this case, you can pass your event aggregator object as an option to each of your views when you instantiate them, so that they can both trigger events or bind to events on a common object (i.e. your event aggregator).
whatsUp = _.extend({}, Backbone.Events) // the aggregator
myFirstView = new FirstBBView ({whatsUp: whatsUp});
(the aggregator shows up as this.options.whatsUp inside the view)
mySecondView = new SecondBBView2 ({whatsUp: whatsUp});
inside FirstBBView:
this.options.whatsUp.bind('specialEvent', function(arg1,arg2) {
// do stuff
});
inside SecondBBView, when something important happens:
this.options.whatsUp.trigger('specialEvent', {arg1: 'some data', arg2: 'more data'});
For a great explanation, see this great article by Derick Bailey