【发布时间】:2012-06-11 16:48:09
【问题描述】:
我在控制台记录 observables 上看到了 cmets,但它似乎对我不起作用。此外,我的应用程序没有以我期望的默认 var 启动。 这两个问题放在一起是因为我怀疑它们在某种程度上是相关的。
HTML
<select data-bind="options: widgets, optionsText: 'name', value: current_widget, optionsCaption: 'Choose...'"></select>
<input data-bind="value: current_widget() ? current_widget().name : 'nothing'" />
Javascript
var cdta = {};
$(document).ready(function(){
cdta.widgets_data = [{ "name": "foo", "id": "1"},{ "name": "bar", "id": "2"},{ "name": "bash", "id": "3"},{ "name": "baq","id": "4"}];
cdta.local = {};
cdta.local.current_widget = { "name": "foo", "id": "1"};
alert('current_widget starting value should be: ' + cdta.local.current_widget.name);
function app() {
var self = this;
//widgets
self.widgets = ko.observableArray(cdta.widgets_data);
// which widget to display from a local source
alert('about to asign a current_widget named:' + cdta.local.current_widget.name);
self.current_widget = ko.observable(cdta.local.current_widget);
}
ko.applyBindings(new app());
alert('after applying bindings name of current widget: ' + current_widget().name);
//expecting foo
//but doesn’t alert because current_widget isnt defined
});
【问题讨论】:
-
@AlfeG 感谢您解决了变量问题
-
@Roman Bataev 也感谢关于 optionsCaption 的第 2 部分 - 这是一个真正的陷阱