在knockoutjs中如何将当前项目引用传递给函数?
我有一个我正在循环的照片库,当用户点击照片时,我想检查用户选择的照片是否在img标签中有特定的类。
这是我当前的代码无效。
my.Character = function () {
var self = this;
self.text = ko.observable();
self.value = ko.observable();
self.image = ko.observable();
self.imageSrc= ko.computed(function () {
return "/Images/" + self.image();
}, this);
self.selected = function ($data) {
if ($data.hasClass('selected')) {
// do stuff here
};
};
视图
<div id="thumbnailsgall" data-bind='foreach: Characters'>
<a data-bind="click: function () { getImage(); }, attr: { rel: image, id: value }" class="thumb_nail" href="#">
<img class="inactive" data-bind="click: function () { selected($data); }, attr: { src: imageSrc }" />
</a>
</div>
答案 0 :(得分:1)
使用css binding:
非常简单我想在父上下文中有一个Characters数组,它应该如下所示:
my.Parent = function(){
var self = this;
self.Characters = ko.observableArray();
// stores the selected character
self.selected = ko.observable();
self.select = function (character) {
if(self.selected() === character)
self.selected(null);
else
self.selected(character);
};
};
my.Character = function () {
self.text = ko.observable();
self.value = ko.observable();
self.image = ko.observable();
self.imageSrc= ko.computed(function () {
return "/Images/" + self.image();
}, this);
};
视图
<div id="thumbnailsgall" data-bind='foreach: Characters'>
<a data-bind="click: function () { getImage(); }, attr: { rel: image, id: value }" class="thumb_nail" href="#">
<img class="inactive" data-bind="click: $parent.select, attr: { src: imageSrc }, css :{'selected' : $parent.selected() === $data}" />
</a>
</div>
请注意,当KO调用select函数时,KO将隐式传递绑定的viewmodel和事件(单击:$ parent.select)。 在其他KO电话
$parent.select($data, clickEvent)
这就是我能写的原因:
self.select = function (character) {};