2014-01-28 48 views
1

繼續在這裏理解KO。我有一個參數的KO方法之一,它工作時,我傳遞一個明確的價值,但是當我調用該函數與無參數沒有給出KnockoutJS函數的參數在未定義時返回viewModel

<button data-bind="click:LaterCall">click</button> 


function InvoiceViewModel() { 

    //Data 
    var self = this; 
    self.LaterCall = function (arg) { 
     console.log(arg); // why is this not undefined???? 
    }; 

} 
var viewModel = new InvoiceViewModel(); 
ko.applyBindings(viewModel); 

http://jsfiddle.net/sajjansarkar/9TMv2/2/

回答

4

淘汰賽的click結合(和event綁定,其中click是子集)傳遞當前數據作爲第一個參數,並將event作爲第二個參數傳遞給任何處理程序。

因此,arg將等於您的情況下您的viewModel

1

參數arg將引用父項,正如您在示例中所見,實際視圖模型是父項。把參數存在主要是用來當你有嵌套控制器和要動態引用父在這裏的第二個例子說,http://knockoutjs.com/documentation/click-binding.html

<ul data-bind="foreach: places"> 
    <li> 
     <span data-bind="text: $data"></span> 
     <button data-bind="click: $parent.removePlace">Remove</button> 
    </li> 
</ul> 

<script type="text/javascript"> 
    function MyViewModel() { 
     var self = this; 
     self.places = ko.observableArray(['London', 'Paris', 'Tokyo']); 

     // The current item will be passed as the first parameter, so we know which place to remove 
     self.removePlace = function(place) { 
      self.places.remove(place) 
     } 
    } 
    ko.applyBindings(new MyViewModel()); 
</script> 

我也建議你不要使用self在JavaScript中的參數名稱,而不是去that

var that = this;