I have an Object having two properties one string and another object. I am unable to create observable on object correctly using KnockOutJS. I do not know what mistake I am performing.
Here is my exact requirement: When I hover on Data Source it should show me all the configured DataSources and once I click on any one of them it Data Source should change to selected Data Source.
JS
function View(data) {
this.Name = ko.observable(data.Name);
console.log("View : " + this.Name());
this.DataSource = ko.observable();
if (data.DataSource) {
this.DataSource(new DataSource(data.DataSource));
console.log("View.DataSource.Name" + this.DataSource.Name());
}
}
function DataSource(data) {
console.log(JSON.stringify(data));
this.Name = ko.observable(data.Name);
console.log("DataSource : " + this.Name());
}
function ViewController() {
var self = this;
self.View = new View({
Name: 'Untitled',
DataSource: null
});
self.View.DataSource(new DataSource({}));
self.DataSources = ko.observableArray([]);
self.HideDS = function () {
console.log("Hide");
jQuery("#SelectDataSource").hide();
}
self.ShowDS = function () {
console.log("Show");
jQuery("#SelectDataSource").show();
}
self.SelDS = function (DS) {
self.HideDS();
self.View.DataSource(new DataSource(DS));
};
var GetDataSourcesSuccess = function (data) {
self.DataSources(jQuery.map(data, function (item) {
return new DataSource(item);
}));
}
GetDataSourcesSuccess([{
Name: "DS A"
}, {
Name: "DS B"
}])
}
ko.applyBindings(new ViewController());
HTML
<button type="button" class="btn btn-default" data-bind="event: { mouseover: ShowDS } , text: View.DataSource.Name == undefined? 'Data Source' : View.DataSource.Name "></button>
<div class="btn-group btn-group-sm hidden-selector" id="SelectDataSource" data-bind="foreach: DataSources , event: { mouseover: ShowDS , mouseout: HideDS }" style="display:none;">
<button type="button" class="btn btn-default" data-bind="text: Name, click: $parent.SelDS"></button>
</div>
Fiddle : http://jsfiddle.net/techphernalia/LDpgL/9/
Problem solved
JS
self.SelDS = function (DS) {
self.HideDS();
self.View.DataSource(new DataSource(DS));
};
HTML
<button type="button" class="btn btn-default" data-bind="event: { mouseover: ShowDS } , text: View.DataSource().Name()? View.DataSource().Name() : 'Data Source' "></button>