I am trying to build a very specific module that integrates Twitter bootstrap (for the tabs), jQuery (for ease of development) and knockout.js for client-side view models. The idea is that I have one HTML page, which has 3 div’s defined in it. Each div is a tab, with only one div visible at a particular time. When a div is displayed it should call a load method on a knockout.js viewmodel that is scoped to the tab and reload the data from the server.
I have written the following code (which works), however it is very specific to a particular tab in my application.
// only configure this once the DOM is ready for processing.
// this code snippet is very long winded and quite a hack, however it allows the content of a bootstrap.js
// tab to be reloaded when the tab is made visible. It does this by calling the LoadCategory() method on the
// knockout.js view model.
//
// it is also worth noting that the view model is bound using knockout to only descendents of the div that contains
// the tab contents. This is to ensure that we can have several knockout view models in one page without needing to
// worry about them interfering with each other.
$(document).ready(function () {
// initialise the model...
var todaysQuestionsModel = new ViewModel(categoryId);
// if this tab is visible to begin with, load the view model.
if ($('#todays-questions').hasClass('active')) {
todaysQuestionsModel.LoadCategory();
}
// only apply these bindings to the elements that descend from the div that contains this tab.
ko.applyBindings(todaysQuestionsModel, document.getElementById("#todays-questions"));
$('a[data-toggle="tab"]').on('shown', function (e) {
if (e.target.hash == '#todays-questions') {
todaysQuestionsModel.LoadCategory();
}
});
});
I would like to be able to wrap this up in a javascript module that I can reuse for different parts of my application, however I am at a loss as to how to generify this code. Ideally I would like to be able to just make a simple function call to configure all of this behaviour automatically.
I assume for the part where the todaysQuestionsModel.LoadCategory() call is made that this should be a callback function. I also assume there should be some way that I don’t have to specify the id selector, but any attempt I have made so far doesn’t seem to work.
Could someone help me out with this, I am quite out of my depth here :-).
Cheers,
Aidan
I would use the event handling by knockout.
This is a modified sample code: http://jsfiddle.net/xVxKD/52/