2012-02-09 43 views
0

我已经看到控制台日志observables的意见,但它似乎并没有为我工作。另外我的应用程序没有启动我预期的默认变量。 这两个问题是在一起,因为我怀疑他们有某种关系。淘汰赛控制台日志和观察未定义

Here is the fiddle

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 
}); 
+0

@AlfeG感谢的是解决了可变问题 – 2012-02-09 23:07:39

+0

@Roman Bataev感谢也为第2部分有关optionsCaption - 这是一个真正的疑难杂症 – 2012-02-09 23:08:39

回答

2

在你的代码中有几个问题。

  1. current_widget是应用程序的属性,所以你需要做这样的事情

    var app = new app(); 
    ko.applyBindings(app); 
    alert('after applying bindings name of current widget: ' + app.current_widget().name); 
    
  2. 由于您使用的价值和optionsCaption bidnings,淘汰赛将设置观察到的一个绑定,以价值为undefined默认。如果你删除optionsCaption绑定它会工作。如果你需要optionsCaption,你需要选择的初始值,你将不得不申请绑定后,将其重置:

    var app = new app(); 
    ko.applyBindings(app); 
    app.current_widget(cdta.widgets_data[0]); //you have to select an object from the array, not a completely unrelated object cdta.local.current_widget 
    alert('after applying bindings name of current widget: ' + app.current_widget().name); 
    

更新: 我错了#2。应用绑定后,您不必重置值。真正的问题是你使用完全不相关的对象(不是数组)来获得初始值。这将解决这个问题:

cdta.local.current_widget = cdta.widgets_data[0]; 
1

但变量/方法current_widget确实不确定。 KnockoutJS不会生成全局变量。

如果你想访问viewModel以外的viewModel数据,那么你需要将它存储在某个地方(变量,窗口​​等)。

var cdta = {}; 
$(document).ready(function(){  
    //...  
    function app() { 
     //... 
    } 
    window.app = new app(); 
    ko.applyBindings(window.app); 

    alert('after applying bindings name of current widget: ' 
     + window.app.current_widget().name); 
    //expecting foo 
});