问题
I am passing $index
and $data
to the change_model
function. The function is expecting 2 parameters in the following order: (index, data)
.
From the viewModel I am passing click: $root.change_model.bind($data, $index())
. Within the function index
prints $data
, and data
prints index
: values are reversed.
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:
The first argument of bind
will become this
inside your function, because Knockout is merely using the regular bind function.
You can either pass $data
or $root
as the first (thisArg
) argument, or pass null or undefined, as you don't really need it since you seem to use the self = this
idiom.
For example:
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>
来源:https://stackoverflow.com/questions/30926278/passing-index-and-data-as-arguments-to-function-for-click-handler