Backbone.Marionette collection iterator as part of itemview classname - marionette

I'm still learning Backbone and Marionette so forgive me if this is trivial.
I have a Backbone.Marionette.CompositeView that I iterate over to render a collection of Backbone.Marionette.ItemView.
My ItemView renders with a className: 'column'.
Is there a way to add the iterator as part of the className for each ItemView?
What I'm trying to accomplish is that the elements render as following:
<div class="column column-1"></div>
<div class="column column-2"></div>
<div class="column column-3"></div>
...
I couldn't find a suitable solution in the docs nor other questions here.
Thanks!

Essentially what you need to know is the index of the itemView model in your collection. Something like this will work:
// Create an itemView
var itemView = Backbone.Marionette.ItemView.extend({
template: "#item-template",
onRender: function () {
this.$el.addClass('class-nr-' + this.options.itemIndex);
}
});
// Create a collectionView
var colView = Backbone.Marionette.CollectionView.extend({
collection: colInstance,
itemView: itemView,
itemViewOptions: function (model, index) {
return {
itemIndex: index
};
}
});
See this fiddle: http://jsfiddle.net/Cardiff/VTkB2/2/
Documentation: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md#collectionviews-itemviewoptions

Related

Get index within v-for using computed or method

I was wondering if it is possible in vue to get the index of an object array directly within the v-for in and pass this value to a computed property or a method, similar to this here, or even a computed property
<div v-for="(object, index) in objects(index)"></div>
methods: {
objects(index){
const categoryId = Object.keys(this.data);
return this.data[categoryId[index]].extras;
}
}
I need to have the index as it is more convenient for me to return the correct value based on defined key, is there some way to achieve this?
Transform your data using a computed value and loop over that. I am not sure what your this.data looks like, but something like this should work (tweak it to suit your needs):
<div v-for="object in computed_objects"></div>
computed: {
computed_objects(){
return Object.keys(this.data).map(categoryId => this.data[categoryId].extras)
}
}
You can bind a method call on each element created by the v-for directive, so for example any time a user clicks on <li> element, it will gets the index of that clicked item:
new Vue({
el: '#app',
data: {
clickedIndex: null,
weekDays: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
},
methods: {
handleClick(i) {
this.clickedIndex = i;
}
}
})
Vue.config.productionTip = false;
Vue.config.devtools = false;
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<ul>
<li v-for="(day,i) in weekDays" v-on:click="handleClick(i)">{{day}}</li>
</ul>
<p>Index clicked {{ clickedIndex }}</p>
</div>

Apply binding once in knockout component

In my web application I have (let's say) 2 tabs, both are custom knockout components. Their visibility is controlled by the following syntax:
<div id="page" data-bind="component: { name: currentTab }"></div>
where currentTab is an observable with the name of the current tab.
In both tabs I have visualisations with D3.js, using custom bindings. The problem is that these custom bindings are reinitialised after opening a tab. Is there a way to only load them once so that they don't need to be redrawn?
Note that the component's viewmodels aren't reinitialised, as they are created with the { instance: new viewModel() } trick:
define(['knockout', 'text!./tab-one.html', 'jquery'], function(ko, template, $) {
function ViewModel() {
var self = this;
};
return {
viewModel: { instance: new ViewModel() },
template: template
};
});
You may need to change slightly your approach:
<div id="page">
<div id="tab-1" data-bind="visible: (currentTab() == 'drawing-1'), component:{name:'drawing-1'}"></div>
<div id="tab-2" data-bind="visible: (currentTab() == 'drawing-2'), component:{name:'drawing-2'}"></div>
</div>
As alternative, you can add some more flexibility to your components if you provide a viewmodel, for example to encapsulate the logic of the visibility inside the component itself, and moreover - if you can also eventually skip the first redraw at component initialization:
This is just an example, but you can see the idea:
ko.components.register('drawing', {
viewModel: function(params) {
// Behaviors
this.active1 = params.currentTab == 'drawing-1';
this.active2 = params.currentTab == 'drawing-2';
this.draw = ko.computed(function() {
if (!ko.computedContext.isInitial()) {
// do some changes to the drawing
}
});
},
template:
'<div data-bind="visible: active1">'+
// drawing 1
'</div>'+
'<div data-bind="visible: active2">'+
// drawing 2
'</div>'
});

Updating a CompositeView when an Item is removed from it's collection

I have a Marionette.CompositeView. I added the ability to remove an item from an item from the collection in the Composite's item view. The CompositeView displays a summary- which is nothing more than the count of items in it's collection.
What is the best way to update the CompositeView when an item is deleted:
app = new Marionette.Application()
app.addRegions
main: '#main'
app.module 'Views', (views, app)->
views.MyItemView = Marionette.ItemView.extend
template: '#my-view-template'
tagName: 'li'
events:
'click' : ()->
#model.collection.remove #model
views.MyCompositeView = Marionette.CompositeView.extend
itemView: views.MyItemView
template: '#my-composite-view-template'
itemViewContainer: 'ul'
initialize: ()->
#model = new Backbone.Model
count: #collection.length
#collection.on 'remove', ()->
console.log 'remove'
app.on 'start', ->
app.main.show new app.Views.MyCompositeView
collection: new Backbone.Collection [
new Backbone.Model( foo: 'bar')
new Backbone.Model( foo: 'bar')
new Backbone.Model( foo: 'bar')
]
$ ()->
app.start()
and here is the html
<div id="main">Hello world</div>
<script type='htm/text' id='my-view-template'>
I am dynamic <em><%= foo %></em>
</script>
<script type='html/text' id='my-composite-view-template'>
<div id='counter'><%= count %></div>
<ul></ul>
</script>
Collection and composite views will rerender child item views (and/or remove individual item views). In your case, you want to rerender the entire composite view when the collection is added to or subtracted from. For that purpose, bind the render method to the appropriate collection events in your view definition:
collectionEvents: {
"add": "render",
"remove": "render"
}

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?
My main page has a DropDownList (DropDownListFor) and a partial view which ONLY contains a list of "items". The items shown in this partial view are dependent upon the item selected in the DropDownList. There's a 1 to many relationship between the DropDownList item and the items in the partial view. So, when the user changes the value of the DropDownList, the content in the partial view will dynamically change to reflect the item selected in the DropDownList.
Here's my DropDownList:
<div data-role="fieldcontain">
Choose Capsule:<br />
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules" })
<br />
</div>
Here's my Partial View declaration on the same page:
<div data-role="fieldcontain">
#Html.Partial("_FillerPartial", Model.Fillers)
</div>
I'm not very familiar with Ajax, but looking at other examples, here's what I have for my Ajax:
$(document).ready(function () {
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
alert("server returned: " + data);
}
});
});
});
And finally, here's a screenshot of what's going on. By changing the "Choose Capsule" drop down list, I want the Filler list to update dynamically:
You can load the drop down list as a partial view from the controller using ajax.
The controller code:
[HttpGet]
public virtual ActionResult GetFillersByCapsule(string cappk)
{
var model = //Method to get capsules by pk, this returns a ViewModel that is used to render the filtered list.
return PartialView("PartialViewName", model);
}
The main view html:
<div id="filteredList">
</div >
The partial view
#model IEnumerable<MyCapsuleModel>
foreach (var x in Model)
{
//Render the appropriate filtered list html.
}
And you can load the filtered list using ajax:
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
$("#filteredList").empty();
$("#filteredList").html(data);
}
});
});
Hope this helps.
You can't update the partial, per se, because the partial will never be rendered again without a page reload. Once you receive the HTML, ASP is done, you're on your own at that point.
What you can do, of course, is switch out the content of a particular div or whatever using JavaScript. Your example in particular screams Knockout, so that's what I would recommend using.
Change your HTML to add a data-bind to your containing div:
<div data-role="fieldcontain" data-bind="foreach: filler">
<button data-bind="text: name"></button>
</div>
And your DropDownList:
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules", data_bind = "event: { change: updateFillers }" })
Then, some JavaScript:
var FillersViewModel = function () {
var self = this;
self.fillers = ko.observableArray([]);
self.updateFillers = function () {
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
self.fillers(data.fillers) // where `fillers` is an array
}
});
}
}
var viewModel = new FillersViewModel();
ko.applyBindings(viewModel);
This is a very simplistic example, and you'll need to do some more work to make it do everything you need it to do in your scenario, but the general idea is that every time the dropdown list is changed, Knockout will call your updateFillers method, which will execute the AJAX and put new data into the fillers observable array. Knockout automatically tracks changes to this array (hence the "observable" part), so an update is automatically triggered to any part of your page that relies on it. In this scenario, that's your div containing the buttons. The foreach binding will repeat the HTML inside for each member of the array. I've used a simple button element here just to illustrate, but you would include the full HTML required to create your particular button like interface. The text binding will drop the content of name in between the opening and closing tag. Refer to: http://knockoutjs.com/documentation/introduction.html for all the binding options you have.
There's much more you could do with this. You could implement templates instead of hard-coding your HTML to be repeated in the foreach. And, you can use your partial view to control the HTML for this template. The important part is that Knockout takes the pain out of generating all this repeating HTML for you, which is why I recommend using it.
Hope that's enough to get you started.

multiple knockout bindings and sharing them

So I have a scenario where I am have knockout binding on my main page.
Index.cshtml:
<div data-bind="foreach breadcrumbs">
<div>
<script>
var IndexViewModel = function () {
var self = this;
self.breadcrumbs = ko.observableArray();
};
ko.applyBindings(IndexViewModel);
</script>
And a Partial View that loads inside the Index.cshtml. The partial view has its own knockout bindings:
<div id="someId">
</div>
<script>
var PartialViewModel = function () {
var self = this;
self.someFunction = function(){
// Access Breadcrumbs here
};
};
ko.applyBindings(PartialViewModel, "someId");
</script>
I want to access the breadcrumbs observableArray from the second partial view and add items to them. I am not even sure if this possible. Please help. I am also using sammy.js but for this purpose its not that relevant.
I don't like having to have dependencies between view models, so I've previously used a jQuery pubsub plugin to allow view models to talk to each other in a decoupled manner. You can see an example of it in this answer
Basically, when you update the breadcrumb, call publish with the new array, and the other view model would subscribe to that event.
An easy solution (but not very clean one) would be to store the indexViewModel in a global variable.
Index.cshtml:
var IndexViewModel = function () {
var self = this;
self.breadcrumbs = ko.observableArray();
};
// we create a global variable here
window.indexViewModel = new IndexViewModel();
ko.applyBindings(window.indexViewModel);
And then you can access this indexViewModel from your partial view model:
var PartialViewModel = function () {
var self = this;
self.someFunction = function(){
// Access Breadcrumbs here
// better use some wrapping functions
// instead of accessing the array directly
window.indexViewModel.breadcrumbs.push({});
};
};
ko.applyBindings(new PartialViewModel(), "someId");
</script>

Resources