2012-02-09 39 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 
});