在我目前的项目中,我正在使用一个下划线过滤器,它对我的小提琴起作用,但对我当前的项目不起作用,我想做的是使用一个淘汰过滤器,但我不知道该怎么做。
这是我使用下划线过滤器的原因
HTML
<div data-bind="foreach: items">
<div class="profile" data-bind="text: name, click: $parent.clicked, enable: active, css:{highlight: active()}"></div>
</div>
<hr>
<h2>Selected Card</h2>
<div data-bind="foreach: selectedItems">
<div data-bind="text: name"></div>
</div>
<input type="button" data-bind="click: save" value="Save">
CSS
.profile {
width: 50px;
height: 80px;
color: black;
background-color:silver;
border: 1px solid black;
float: left;
line-height:80px;
text-align: center;
margin: 2px;
}
.highlight {
background: yellow !important;
border:1px solid #000;
color: black;
}
javascript
function Card(number) {
this.active = ko.observable(false);
this.name = ko.observable(number);
}
var model = function () {
var cards = [1, 2, 3, 5, 8, 13, 20, 40, 100];
for (var i = 0 ; i < cards.length ; i++)
cards[i] = new Card(cards[i]);
var items = ko.observableArray(cards)
var selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
var clicked = function (item) {
items().forEach(function (item) { item.active(false) });
item.active(!this.active());
};
var save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}
ko.applyBindings(model);
答案 0 :(得分:1)
如果您没有正确设置,可能会对此关键字感到困惑。我建议你使用self关键字来解决你的困惑。另外,我看到你的揭示模块模式最后缺少括号。这是固定的JavaScript:
function Card(number) {
this.active = ko.observable(false);
this.name = ko.observable(number);
}
var model = function () {
var self = this;
self.cards = [1, 2, 3, 5, 8, 13, 20, 40, 100];
for (var i = 0 ; i < cards.length ; i++)
cards[i] = new Card(cards[i]);
self.items = ko.observableArray(cards)
self.selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
if(item.active())
{
return item;
}
});
})
self.clicked = function (item) {
item.active(true);
};
self.save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}();
ko.applyBindings(model);
您可以查看更新后的JSFiddle here。
此外,如果您不想使用下划线过滤选项,您也可以使用淘汰赛过滤器:
function Card(number) {
this.active = ko.observable(false);
this.name = ko.observable(number);
}
var model = function () {
var self = this;
self.cards = [1, 2, 3, 5, 8, 13, 20, 40, 100];
for (var i = 0 ; i < cards.length ; i++)
cards[i] = new Card(cards[i]);
self.items = ko.observableArray(cards)
self.selectedItems = ko.computed(function () {
return ko.utils.arrayFilter(self.items(), function(item) {
if(item.active())
{
return item;
}
});
});
self.clicked = function (item) {
item.active(true);
};
self.save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}();
ko.applyBindings(model);
这是second option的JSFiddle。