How to display an item view with no tag - backbone.js

The problem is I want to render option elements with the value attribute set as well as the text node.
So setting tagName to option in my ItemView does not just do this. The solution I have at the moment is to set it to option and then use the following code in the ItemView constructor to set the value attibute:
onRender: function () {
this.$el.attr('value', this.model.get('name'));
}
This works.
But is there any other way?
What I'd really like to do is just tell Marionette not to output an element at all and then in my ItemView template have this:
<option value="<%= name %>"> <%= name %> </option>
Is this possible?

It's possible but a bit fiddly, by default Backbone always uses a wrapper element (definable by using tagName) but you'd have to expressly populate the attributes (as you are doing above).
It is however possible to circumvent the wrapper element using a slightly convoluted setElement approach and this will enable you keep all markup in a template with attributes on the root node populated from the model. I like this approach as well since I personally think it keeps a clearer separation of concerns.
Take a look here for an example - Backbone, not "this.el" wrapping
Not sure if Marionette has a build in mechanism for doing this.

I am not sure you should from all different kind of reasons.
But I understand that in the use case of a single tag view, the way Marionette/Backbone work you either create another tag and have a view, or you use onRender and query to update the single tag that was already generated for you.
You could have this Object that will extend ItemView, lets call it SingleTagView. Basicly I am extending ItemView and using overrunning it's render function with one change.
Instead of doing:
this.$el.html(html);
I am doing:
var $html = $(html);
this.$el.replaceWith($html);
this.setElement($html);
Here is the code:
var SingleTagView = Marionette.ItemView.extend({
render: function() {
this.isClosed = false;
this.triggerMethod("before:render", this);
this.triggerMethod("item:before:render", this);
var data = this.serializeData();
data = this.mixinTemplateHelpers(data);
var template = this.getTemplate();
var html = Marionette.Renderer.render(template, data);
// above is standart ItemView code
var $html = $(html);
this.$el.replaceWith($html);
this.setElement($html);
// this code above replaced this.$el.html(html);
// below is standart ItemView code
this.bindUIElements();
this.triggerMethod("render", this);
this.triggerMethod("item:rendered", this);
return this;
}
});
If you are going to use this kind of angle, make sure you test the behavior properly (event handling, Dom leaks, different flows with before:render events).

I would try:
var optionTag = Marionette.ItemView.extend({
tagName: "option",
initialize: function(){
this.attributes = {
value: this.model.get('name');
}
}
}
Backbone should then do the rest (i.e. putting the content of attributes into the HTML tag)...

Related

Where do you put this kind of controller code in an angular app?

The following code is needed in 2 different controllers (at the moment, maybe more controllers later). The code works around a problem I've found in ng-grid and allows the delayed selection of a row (once the data has been loaded).
// Watch for the ngGridEventData signal and select indexToSelect from the grid in question.
// eventCount parameter is a hack to hide a bug where we get ngGridEventData spam that will cause the grid to deselect the row we just selected
function selectOnGridReady(gridOptions, indexToSelect, eventCount) {
// Capture the grid id for the grid we want, and only react to that grid being updated.
var ngGridId = gridOptions.ngGrid.gridId;
var unWatchEvent = $scope.$on('ngGridEventData', function(evt, gridId) {
if(ngGridId === gridId) {
//gridEvents.push({evt: evt, gridId:gridId});
var grid = gridOptions.ngGrid;
gridOptions.selectItem(indexToSelect, true);
grid.$viewport.scrollTop(grid.rowMap[0] * grid.config.rowHeight);
if($scope[gridOptions.data] && $scope[gridOptions.data].length) {
eventCount -= 1;
if(eventCount <= 0) {
unWatchEvent(); // Our selection has been made, we no longer need to watch this grid
}
}
}
});
}
The problem I have is where do I put this common code? It's obviously UI code, so it doesn't seem like it belongs in a service, but there is no classical inheritance scheme (that I have been able to discover) that would allow me to put it in a "base class"
Ideally, this would be part of ng-grid, and wouldn't involve such a nasty hack, but ng-grid 2.0 is closed to features and ng-grid 3.0 is who knows how far out into the future.
A further wrinkle is the $scope that I guess I would have to inject into this code if I pull it from the current controller.
Does this really belong in a service?
I would probably just put this in a service and pass $scope into it but you do have other options. You may want to take a look at this presentation as it covers different ways of organizing your code: https://docs.google.com/presentation/d/1OgABsN24ZWN6Ugng-O8SjF7t0e3liQ9UN7hKdrCr0K8/present?pli=1&ueb=true#slide=id.p
Mixins
You could put it in its own object and mix it into any controllers using angular.extend();
var ngGridUtils = {
selectOnGridReady: function(gridOptions, indexToSelect, eventCount) {
...
}
};
var myCtrl = function() {...};
angular.extend(myCtrl, ngGridUtils);
Inheritance
If you use the 'controller as' syntax for your controllers then you can treat them like classes and just use javascript inheritance.
var BaseCtrl = function() {
...
}
BaseCtrl.prototype.selectOnGridReady = function(gridOptions, indexToSelect, eventCount) {
...
};
var MyCtrl = function() {
BaseCtrl.call(this);
};
MyCtrl.prototype = Object.create(BaseCtrl.prototype);
HTML:
<div ng-controller="MyCtrl as ctrl"></div>

Backbone / Marionette ItemView strategy

I'm in the process of setting up a website with a blog that has some peculiarities. It's sort of a tumblr-esque experience, where there's different post-type:
Facebook-post
Quote
Article
Research
These posts share some common attributes such as id, title, post_date, post_url_slug, but some have a post_image or post_external_link for example. This is all dependent on the post_type, which can hold values such as facebook, quote, article etc. What would be a good strategy to determine which type it is when rendering a Marionette.CollectionView and either selecting a different tempalte altogether or handling this in the template with underscore's arbitrary javascript in my template? Any input would be appreciated.
Thanks!
Definitely don't put the logic in the view template. That will lead to pain, suffering, hate and the dark side. :P
You can override the getItemView method on the CollectionView or CompositeView and use that to determine which view type you want. https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.collectionview.js#L122
var Stuff = Marionette.CollectionView.extend({
// ...,
getItemView: function(item){
var type = item.get("whatever_field");
var viewType;
if (type === "some value"){
viewType = SomeViewType;
} else {
viewType = AnotherViewType;
}
return viewType;
}
});
You should have one single ItemView, don't need to override getItemView of the CollectionView. The ItemView should be the one in charge of deciding the template to use, that's what getTemplate is for. It should look like this:
var MyItemView = Marionette.ItemView.extend({
getTemplate: function() {
var template;
switch(this.model.get('type')) {
case 'facebook':
template = 'Template for Facebook type';
break;
case 'quote':
template = 'Template for Quote type';
break;
case 'article':
template = 'Template for Article type';
break;
}
return template;
}
});
This way you only have one ItemView for the one model you have and the rendering decisions are left to the template as it should be.
You could handle this in the ItemView intialize function and switch the template there. So long as you are planning to use the same events cross post type

In Backbone.js how do you handle Ordinal Numbering and changing numbering based on jQuery Sortable in the view?

Here is my situation. I have a bunch of "Question" model inside a "Questions" collection.
The Question Collection is represented by a SurveyBuilder view.
The Question Model is represented by a QuestionBuilder view.
So basically you have an UL of QuestionBuilder views. The UL has a jQuery sortable attached (so you can reorder the questions). The question is once I'm done reordering I want to update the changed "question_number"s in the models to reflect their position.
The Questions collection has a comparator of 'question_number' so collection should be sorted. Now I just need a way to make their .index() in the UL reflect their question_number. Any ideas?
Another problem is DELETEing a question, I need to update all the question numbers. Right now I handle it using:
var deleted_number = question.get('question_number');
var counter = deleted_number;
var questions = this.each(function(question) {
if (question.get('question_number') > deleted_number) {
question.set('question_number', question.get('question_number') - 1);
}
});
if (this.last()) {
this.questionCounter = this.last().get('question_number') + 1;
} else {
this.questionCounter = 1;
}
But it seems there's got to be a much more straighforward way to do it.
Ideally whenever a remove is called on the collection or the sortstop is called on the UL in the view, it would get the .index() of each QuestionuBuilder view, update it's models's question_number to the .index() + 1, and save().
My Models,Views, and Collections: https://github.com/nycitt/node-survey-builder/tree/master/app/js/survey-builder
Screenshot: https://docs.google.com/file/d/0B5xZcIdpJm0NczNRclhGeHJZQkE/edit
More than one way to do this but I would use Backbone Events. Emit an event either when the user clicks something like done sorting, hasn't sorted in N seconds, or as each sort occurs using a jQuery sortable event such as sort. Listen for the event inside v.SurveyBuilder.
Then do something like this. Not tested obviously but should get you there relatively easily. Update, this should handle your deletions as well becuase it doesn't care what things used to be, only what they are now. Handle the delete then trigger this event. Update 2, first examples weren't good; so much for coding in my head. You'll have to modify your views to insert the model's cid in a data-cid attribute on the li. Then you can update the correct model using your collection's .get method. I see you've found an answer of your own, as I said there are multiple approaches.
v.SurveyBuilder = v.Page.extend({
template: JST["app/templates/pages/survey-builder.hb"],
initialize: function() {
this.eventHub = EventHub;
this.questions = new c.Questions();
this.questions.on('add', this.addQuestion, this);
this.eventHub.on('questions:doneSorting', this.updateIndexes)
},
updateIndexes: function(e) {
var that = this;
this.$('li').each(function(index) {
var cid = $(this).attr('data-cid');
that.questions.get(cid).set('question_number', index);
});
}
I figured out a way to do it!!!
Make an array of child views under the parent view (in my example this.qbViews maintains an array of QuestionBuilder views) for the SurveyBuilder view
For your collection (in my case this.questions), set the remove event using on to updateIndexes. That means it will run updateIndexes every time something is removed from this.questions
In your events object in the parent view, add a sortstop event for your sortable object (in my case startstop .question-builders, which is the UL holding the questionBuilder views) to also point to updateIndexes
In updateIndexes do the following:
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
And there is my full code for SurveyBuilder view:
v.SurveyBuilder = v.Page.extend({
template: JST["app/templates/pages/survey-builder.hb"],
initialize: function() {
this.qbViews = []; //will hold all of our QuestionBuilder views
this.questions = new c.Questions(); //will hold the Questions collection
this.questions.on('add', this.addQuestion, this);
this.questions.on('remove', this.updateIndexes, this); //We need to update Question Numbers
},
bindSortable: function() {
$('.question-builders').sortable({
items: '>li',
handle: '.move-question',
placeholder: 'placeholder span11'
});
},
addQuestion: function(question) {
var view = new v.QuestionBuilder({
model: question
});
//Push it onto the Views array
this.qbViews.push(view);
$('.question-builders').append(view.render().el);
this.bindSortable();
},
updateIndexes: function(){
//Go through each of our Views and set the underlying model's question_number to
//whatever the index is in the list + 1
_.each(this.qbViews, function(qbView){
var index = qbView.$el.index();
//Only actually `set`s if it changed
qbView.model.set('question_number', index + 1);
});
},
events: {
'click .add-question': function() {
this.questions.add({});
},
//need to update question numbers when we resort
'sortstop .question-builders': 'updateIndexes'
}
});
And here is the permalink to my Views file for the full code:
https://github.com/nycitt/node-survey-builder/blob/1bee2f0b8a04006aac10d7ecdf6cb19b29de8c12/app/js/survey-builder/views.js

Add class to elements for values of attribute with Backbone.ModelBinder

I'm using Backbone.ModelBinder in a Backbone.js Marionette project. I've a scenario which I can't work out how to use ModelBinder to automatically update my model/UI.
My model has a 'status' string attribute, with multiple states. In this example I'll show the code for two: 'soon', 'someday'
In my UI I have a list on which I use click events to set the model status, and update classes to highlight the relevant link in the UI.
<dd id="status-soon"><a>Soon</a></dd>
<dd id="status-someday" class="active"><a>Someday</a></dd>
events: {
'click #status-soon': 'setStatusSoon',
'click #status-someday': 'setStatusSomeday'
},
setStatusSoon: function () {
this.model.set('status', 'soon');
this.$el.find('.status dd').removeClass('active');
this.$el.find('#status-soon').addClass('active');
},
... etc
It feels like I doing this a long-winded and clunky way! The code bloat increases with the number of states I need to support. What's the best way of achieving the same outcome with ModelBinder?
You could probably simplify things with a data attribute, something like this:
<dd data-status="soon" class="set-status"><a>Soon</a></dd>
<dd data-status="someday" class="set-status active"><a>Someday</a></dd>
and then:
events: {
'click .set-status': 'setStatus'
},
setStatus: function(ev) {
var $target = $(ev.target);
var status = $target.data('status');
this.model.set('status', status);
this.$el.find('.status dd.set-status').removeClass('active');
$target.addClass('active');
}
You might not need the set-status class, just keying things on the <dd>s might be sufficient; I prefer separating my event handling from the nitty gritty element details though.
Unfortunately, it is going to be pretty difficult to do exactly what you want with ModelBinder. The main reason being that ModelBinder wants to provide the same value for all elements that are part of a single selector. So doing this with ModelBinder, while possible, is going to be pretty verbose as well.
The cleanup offered by mu is likely to be better than trying to use ModelBinder. 1) because you need a click handler to do the this.model.set no matter what and 2) you would need individual bindings for ModelBinder because the converter function is called once for a single selector and then the value is set on all matching elements (rather than looping through each one).
But if you do want to try and do something with ModelBinder it would look something like this:
onRender : function () {
var converter = function (direction, value) {
return (value == "soon" ? "active" : "");
};
var bindings = {
status : {selector : "#status-soon", elAttribute : "class", converter : converter}
};
this.modelBinder.bind(this.model, this.el, bindings);
}
This would do what you want. Of course the down side as I said above is that you will need multiple selector bindings. You could generalize the converter using this.boundEls[0] but you will still need the separate bindings for it to work.
In case you want to access to the bound element, it is possible to declare 'html' as elAttrbute, modify the element and return its html with converter function:
onRender : function () {
var converter = function (direction, value, attribute, model, els) {
return $(els[0]).toggleClass('active', value === 'soon').html();
};
var bindings = {
status : {
selector : "#status-soon",
elAttribute : "html",
converter : converter
}
};
this.modelBinder.bind(this.model, this.el, bindings);
}

Backbone RequireJS and delegateEvents

In my router I require a view like this:
require(['views/business-detail-view'],
function(BusinessDetailView) {
var businessDetailView = new BusinessDetailView({collection: businessOverviewCollection.models[id], id: id});
businessDetailView.render();
}
);
and in the view I'm binding events like this:
events: {
'click #about-btn' : 'aboutHandler',
'click #contact-btn' : 'contactHandler',
'click #deals-btn' : 'dealsHandler',
'click #map-btn' : 'mapHandler'
},
Now the issue is that if the view gets rendered the first times the callbacks are invoked ones. But if the view needs to be rendered again in some other place the callbacks are invoked twice and so on.
How can I prevent this or am I doing something wrong?
UPDATE:
In the meantime I have changed the code in my router to:
if ( !businessDetailView ) {
require(['views/business-detail-view'],
function(BusinessDetailView) {
businessDetailView = new BusinessDetailView({collection: businessOverviewCollection.models[id]});
businessDetailView.render();
}
);
}
else {
businessDetailView.collection = businessOverviewCollection.models[id];
businessDetailView.render();
}
which seem to solve the issue, but I'm still to new to backbone this know whether this is a valid pattern.
At some point in your view you probably clear out the existing HTML on the page and replace it with new HTML. When you clear out old HTML you should also clear out old event handlers so they aren't laying around. For example, in your view when you want to render your newHtml you could do:
#$el.off().html(newHtml)

Resources