Availability of UI elements in Marionette.View - backbone.js

I'd just like to understand the decisions behind Backbone.Marionette's view regarding UI elements.
When instantiating a Marionette.View on an existing DOM element, like this:
view = new Marionette.ItemView({
el: "#element",
ui : {
whatever : "#whatever"
}
});
I am able to access view.$el, the jquery selector inside view.initialize, so far so good.
However, when I try to access view.ui.whatever, I only have access to the selector, ie the string "#whatever" instead of the actual $("#whatever") jquery selector.
The reason for this is because Marionette.View.bindUIElements() is only called on render and not before initialize.
I would like to know if you think this behaviour is logic and why?
I am only asking in the case of attaching of the view to an existing el, if the view is created with a template, I do understand why the binding is in render().

Attaching a view to an existing element is the exception. The normal view lifecycle involves calling render, and without doing that there would be nothing for the UI elements to bind to.
Just call this.bindUIElements() in your initialize method when you need to attach a view to an existing element.

When I am working with Marionette, I put the code that has to access the ui elements inside the onShow method. This event is fired after the dom is ready and the elements are ready to be manipulated. Inside this method, your ui.whatever will now be pointing to an element and not a string.

I think you have that problem because you have to access to the jQuery element with
this.ui.whatever
Because "this" is already a view instance.
See: http://marionettejs.com/docs/v2.4.4/marionette.itemview.html#organizing-ui-elements

Related

How do I properly use $el and .remove() in backbone?

I'm still confused by this. The common paradigm I see emerge is...
view.render()
With render set to
function () { this.$el.html( this.template() ) }
How does this behavior mesh with remove? This renders the view.. but then logically you'll call .remove() to unbind the events and ditch it.. If you use that though, you've ditched the parent container ($el), and can't re-render. The docs need to be explicit then that the convention is to not this.$el.html( this.template() ), but to render the template by calling .html() on some non-el parent element. You can either call .render() using the views own $el and also use .remove().
How does these two work together?
The best practice I see is slightly different. Leave the el property off entirely -- let backbone create its own element. The render method should look like this:
render: function() {
this.$el.html(this.template(some_data_from_somewhere));
return this;
}
and then you call render from the router, thusly:
some_container.append(view.render().el)
If you do it this way, then the default remove implementation:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
}
starts to make more sense. The view created and has sole control of its el so it makes perfect sense for the view to destroy the el when it is being destroyed. The view's owner creates the view and adds it to the page; then later, the view's owner destroys the view (by calling remove) when the owner is done with it. This approach makes the view nicely self-contained.
Of course, if your view is expecting to bind to an existing el or have someone give it an el when it is created, then you're going to have to provide a custom remove to unbind DOM events (by calling this.undelegateEvents() presumably), remove the contents of this.el (but not el itself), etc. Similarly, if your view has child views then you'd provide a remove that would call remove on all the children before cleaning itself up.
I don't think I fully understand your questions; but I think if you look at the sections titled:
Decouple Views from other DOM elements
and
Cleaning Up: Avoiding Memory Leaks and Ghost Views
form the following link, then you might just find the answer that you were looking for.
http://coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/
It was only until recently that I started adding my view to the DOM from outside of the view itself meaning I don't pass in an el: when creating the view. I just have he view render the DOM element from within the view to memory and call render().$el from the calling code to render the view just like the article states.

Test Driving Backbone view events

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.

Dynamically created element used for Raphael canvas

I have created a Backbone.js/Require.js application that dynamically loads HTML templates to use as "pages" in the application. This means my main HTML page looks like so.
<head>
// Necessary CSS and Javascripts here
</head>
<body>
<div id="container"></div>
</body>
And then I used underscore templates to render new elements dynamically to the DOM. However, a new feature requires the use of a Raphael.js chart. I created a new element <div id='canvas'></div> and call Raphael('canvas') but since the canvas element wasn't there on DOM ready, Raphael can't see the newly created element.
I have attempted to use a jQuery selector in place of the id reference like so Raphael($('#canvas')) but this attaches the canvas to the body element and not my container element.
Any suggestions on how to bind a Raphael canvas to a dynamically created element?
Raphael($('#canvas').first(), '100%', '100%')
Though I had errors else where, the main issue that caused Raphael not to fire was forgetting that a jQuery selector passes an array of Elements and Raphael's constructor want's a single element. Raphael was attaching itself to the body because it was the top level parent of the selector's result.
Mosselman was also correct in pointing out that you can build a view in Backbone entirely in memory and then append it to the DOM.
A way to overcome this issue is by creating an empty element in the view and binding everything onto that. I have never worked with Raphael, but I think this could work:
var someView = Backbone.View.extend({
el: document.createElement('div'), // This creates a DOM element '<div></div>'
initialize: function(){
Raphael(this.el); // Attach Raphael, you could also go with jQuery
},
render: function(){
jQuery('#container').append(this.el); // Add to DOM somehow
}
})
seems like a good approach is to either throw an event after the template has been added to the DOM and have your call to Raphael('canvas') listen for that event or use a callback to trigger Raphael('canvas'). in both cases you are ensuring that you don't call Raphael('canvas') before the target element is in place.
very roughly, something like this:
//from your raphael module / code
$(document).on('canvasAdded', function(){
var paper = Raphael('canvas');
//stuff!
});
//after you are sure your template has rendered
$(document).trigger('canvasAdded');
you probably want to make some kind of .init() method and call that from the event handler (vs. what I show above) but hopefully this points you in the right direction.
I know that this is too old question, but anyway it can help to someone. Its important to be sure that your view is placed on page, so use something like onShow functionality, or render. But anyway Raphael will not show right because if your send to Raphael this.$el or anything similar it will not accept it like you expect. What You need to do is something like this.$el.first() or this.$el[0].

Backbonejs: How to unbind collection bindings when a view is removed?

I've got a backbonejs application with two view. It kind of looks like this:
<body>
<header></header>
<div id="content"></div>
</body>
Every time a view is loaded the app overwrites the current view by completely overwriting the contents of #content.
// Like this...
$('#content').html( new primaryView().render() );
// ...and this.
$('#content').html( new secondaryView().render() );
The application has a global collection.
App.Collection();
The secondary view modifies itself depending on the global collection. Therefor it binds a function to the 'add' event' on App.Collection in the views initialize function;
App.Collection.bind('add', function(){
console.log('Item added');
});
Which result in my problem. Every time the secondary view is loaded a new function is binded to App.Collection's add event. If I go from the primary view to the secondary view three times, the function will fire three times everytime an item is added to App.Collection.
What am I doing wrong?
I can see how I would do it if there was an uninitialize function on views.
I can see how I could do it if I never removed a view once it was loaded.
I can see how I would do it if I could namespace events like in Jquery. (by unbinding before binding).
You can generalize your problem quite a bit. Basically, you are writing an event-driven app, and in such app events should be taken care of.
Check out this post to see a recommended way to work with event handlers in backbone.
Depending on the situation, you can use initialize and render methods to handle different aspects of creating a view. For instance, you can put your binding inside the initialize
initialize: function() {
App.Collection.bind('add', function(){
this.view.render()
});
}
which only fires when the view is created. This binds your render method to the add event. Then in your render method you can actually create the html.
This prevents the binding from happening every time you need to re-render.

Correct way to insert a view with Backbone.js

I have a simple backbone.js app. I want to render a view into the DOM of the HTML page, this view is a detail view for a model. My HTML page already has the DIV element that I want to render the view into. If I try to render my view like this:
detailView = new RulesPanelView({model : #model})
$("#detail").html(detailView.render().el)
It fails and I get [Object HTMLDivElement] inserted into the DOM, not my rendered HTML.
This is the only way I can get it to work and it seems like a hack:
$("#detail").html('')
detailView = new RulesPanelView({model : #model})
$("#detail").append(detailView.render().el)
Having to empty the HTML of the DIV before rendering so I don't get multiple views rendered inside #detail which is what would happend with append.
Also aren't I creating way too many views this way, just seems cleaner to replace the HTML as in the first code segment?
What is the correct way to render this view?
What you want is to pass the already inserted DOM node to the view as a 'el' option to the constructor:
new RulesPanelView({el: $("#detail")});
This way, it won't render again. You still need to make sure your view's 'render' method will be able to render a correct view from an updated model, though.
The backbone documentation mentions this as a good way to avoid rendering too much stuff at once.
I actually append in the render method of the view. This doesn't work if you want to re-render when models change - but for that I've added a refresh method that render actually calls before appending. I then bind the refresh to the model change (if I need that). So in my View, I do this:
render: function(){
var markup = this.refresh();
$(markup).appendTo('#some-selector');
return this;
},
refresh: function(){
return $(this.el).html($.mustache(this.template, this.model.toJSON()));
},
Not sure if that's the "best", but I think it works pretty well. I've also seen where you have a collection bound to a view that loops through all of the models and renders "sub-views" of the collection view - this provides a nicer programmatic approach than hard-coding where you're going to append.

Resources