【发布时间】:2014-08-08 12:24:50
【问题描述】:
我有一个对象有两个属性一个字符串和另一个对象。我无法使用 KnockOutJS 在对象上正确创建 observable。我不知道自己犯了什么错误。
这是我的确切要求:当我将鼠标悬停在 Data Source 上时,它应该向我显示所有已配置的数据源,一旦我点击其中任何一个,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>
小提琴:http://jsfiddle.net/techphernalia/LDpgL/9/
问题解决了
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>
【问题讨论】: