Reputation: 376
I have a component which is a drop down menu (Actually a bootstrap button menu). The 'dropdown' gets it's values by doing an AJAX call to the server and parsing a JSON string.
I need this button in multiple places on the page however I need new instances of the component each time as I have to pass in the calling viewmodel to add some data to it.
Obviously every time I include this button the component does an ajax call to get it's values meaning there are n number of AJAX calls to the server. Is there anyway I can just do one Ajax call and propagate it to every instance of the component?
Button component
function AddElement(params) {
this.options = ko.observableArray();
var self = this;
var section = params.section;
$.getJSON("http://localhost:8080/test", function (data) {
elementOptions = data;
self.options(data);
});
this.addElement = function (data) {
section.formElements.push(data);
};
}
So the question is how can I achieve this or is there a better way to implement this kind of functionality in KO (i.e not components)
Thanks
David
Upvotes: 0
Views: 150
Reputation: 4641
Option 1: Do the loading in some common parent of your component and pass in the observable array.
function AddElement(params) {
var self = this,
section = params.section,
options = params.options;
}
Option 2: Pass a loader object to your component.
function AddElement(params) {
var self = this,
section = params.section,
loader = params.loader; //All 'AddElement' components get passed the same instance of the loader
this.options = ko.observableArray();
loader.load(function (data) { //The loader is responsible for doing the AJAX once and only once.
elementOptions = data;
self.options(data);
});
}
Upvotes: 1