基本上我对Knockout很新。我一直在尝试大量的例子,现在我疯了。我正在做的并不困难。但是,它仍然不起作用。
我正在尝试接收数据,将其映射到对象(?),然后使用一些observable进行不同的过滤。这些数据永远不需要写回服务器,只能用于消费。
我的例子:http://jsfiddle.net/boyus/qTb5Q/3/
function Item(id, firstName, lastName, expertise, img, tag) {
this.id = ko.observable(id);
this.firstName = ko.observable(firstName);
this.lastName = ko.observable(lastName);
this.expertise = ko.observable(expertise);
this.img = ko.observable(img);
this.tag = ko.observable(tag);
this.fullName = ko.dependentObservable(function() {
return this.firstName() + " " + this.lastName();
}, this);
this.expertPath = ko.dependentObservable(function() {
return "http://www.example.com/user/" + this.id();
}, this);
this.imgPath = ko.dependentObservable(function() {
return "http://img835.imageshack.us/img835/5116/" + this.img();
}, this);
}
var viewModel = {
items: ko.observableArray([]),
filter: ko.observable()
};
//ko.utils.arrayFilter - filter the items using the filter text
viewModel.filteredItems = ko.dependentObservable(function() {
var filter = this.filter().toLowerCase();
if (!filter) {
return this.items();
} else {
return ko.utils.arrayFilter(this.items(), function(item) {
return (item.fullName().indexOf(filter) > -1);
});
}, viewModel);
var JSONdataFromServer = '[{"id":"1","firstName":"Bill","lastName":"Nye","expertise":"Science Guy", "img":"emptyprofile.png","tag":"environment"},{"id":"54","firstName":"John","lastName":"Dow","expertise":"Software Creation","img":"emptyprofile.png","tag":"software"},{"id": "544","firstName":"Pete","lastName":"Dragon","expertise":"Magic (and Sparkles)","img":"emptyprofile.png","tag": "environment"}]';
var dataFromServer = ko.utils.parseJson(JSONdataFromServer);
//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(dataFromServer, function(item) {
return new Item(item.id, item.firstName, item.lastName, item.expertise, item.img, item.tag);
});
viewModel.items(mappedData);
ko.applyBindings(viewModel);
提前感谢所有帮助。
如果它有帮助(也就是我的代码永远不会工作),我对此代码的未来更新将是:
答案 0 :(得分:1)
针对当前小提琴的具体问题:
filteredItems
声明末尾else
错过了一个大括号toLowerCase()
。我将其更改为将filter
初始化为空字符串。fullName
转换为小写。