[英]How to refer Knockout.js objects and array of objects in right context
I can´t seem to get this right: http://jsfiddle.net/dPyQy/4/ 我似乎无法正确理解: http : //jsfiddle.net/dPyQy/4/
I want to collect the tags I am entering in the input field for saving. 我想收集在输入字段中输入的标签以进行保存。 I need to reference the Textbatches as a SelectedText as in RL I need to be able to choose among Textbatches.
我需要像在RL中一样将Textbatches引用为SelectedText,我需要能够在Textbatches中进行选择。
var Textbatch = function (data,tags) {
var self = this;
self.TextbatchId = data.TextbatchId;
self.Title = ko.observable(data.Title);
self.Text = ko.observable(data.Text);
self.TextTags = ko.observableArray(tags);
function createTypeComputed(tagType) {
return ko.computed(function () {
return ko.utils.arrayFilter(self.TextTags(), function (item) {
return item.Type() == tagType;
});
});
}
self.managerTags = createTypeComputed(0);
self.removeTag = function (tagToRemove) {
self.TextTags.remove(function (item) {
return item.Id == tagToRemove.Id;
});
}
}
Struggling with the contexts and the objects and everything. 挣扎于上下文,对象以及一切。 I want the chosen tags listed beneath the input-field, and then the debug to show the updated object.
我希望所选标签列在输入字段下方,然后进行调试以显示更新的对象。
Any help highly appreciated. 任何帮助,高度赞赏。 Thanx.
感谢名单。
managerTags
evaluates to an array, but you're using it in a text
binding which is expecting it to evaluate to a string. managerTags
计算结果为数组,但是您正在text
绑定中使用它,希望它计算结果为字符串。
How do you want to display it? 您想如何显示它? As an HTML list (use a
foreach
binding to loop over the tags), or as a comma (or something)-separated string (use join
on it)? 作为HTML列表(使用
foreach
绑定来循环标记),还是作为逗号(或其他内容)分隔的字符串(在其上使用join
)?
To get a comma-separated string, change createTypeComputed
to 要获得逗号分隔的字符串,
createTypeComputed
更改为
function createTypeComputed(tagType) {
return ko.computed(function () {
return ko.utils.arrayMap(
ko.utils.arrayFilter(self.TextTags(), function (item) {
return item.Type() == tagType;
}),
function (item) {
return item.Name();
}).join(',');
});
}
Note that if you can count on using an ES5 browser (anything but IE<9) you can simplify the function for the computed to 请注意,如果您可以指望使用ES5浏览器(IE <9以外的任何浏览器),则可以简化用于
return self.TextTags().filter(function (item) {
return item.Type() == tagType;
})
.map(function (item) {
return item.Name();
})
.join(',');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.