2015-06-18 76 views
0

我正在将$index$data传递给change_model函数。该功能按以下顺序预期2个参数:(index, data)

从viewModel我通过click: $root.change_model.bind($data, $index())。在功能index中打印$datadata打印index:数值相反。

self.change_model = function(index, data) { 
    self.patternSelectedIndex(index); 
    selected_door = data.file; 
    create_door(); 
}; 
<div data-bind="foreach: x.patterns"> 
    <div class="thumbnail" data-bind="css: { selected: $index() === $root.patternSelectedIndex() }"> 
     <img class='img model' style='width:164px;height:90px;padding:5px' data-bind="attr:{src:'images/models/' + $data.file + '.png'}, click: $root.change_model.bind($data, $index())" /> 
     <div class="caption"> 
     <span data-bind="text: $data.name"></span> 
     </div> 
    </div> 
</div> 
+1

它可以帮助如果包括* *凌晨一点多的代码,使一个完整的摄制,这使得它更容易让别人帮你。像[这个jsfiddle](http://jsfiddle.net/cz2jw41s/1/)。 – Jeroen

+0

[JavaScript的'绑定'方法的使用]的可能重复(http://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method) – CrimsonChris

回答

2

bind的第一个参数将成为this自己的函数中,因为淘汰赛仅使用the regular bind function

您可以通过$data$root作为第一个(thisArg)的说法,或传递null或undefined,因为你并不真的需要它,因为你似乎使用self = this成语。

例如:

var ViewModel = function() { 
 
    var self = this; 
 

 
    self.change_model = function (index, data) { 
 
     console.log(this); 
 
     console.log(index); 
 
     console.log(data); 
 
     // Actual code here 
 
    }; 
 

 
    self.x = { patterns: [{ file: 'some-file', name: 'some-name' }] }; 
 
}; 
 

 
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 

 
<div data-bind="foreach: x.patterns"> 
 
    <button data-bind="click: $root.change_model.bind($data, $index(), $data)">Click me!</button> 
 
    <span data-bind="text: $data.name"></span> 
 
</div>

+1

你从来没有解释为什么参数似乎颠倒。点击绑定自动将上下文作为参数传递给绑定函数。这意味着您的示例中绑定的第三个参数不是必需的。 – CrimsonChris

相关问题