我对应该绑定(bind)到“src
”属性的计算变量有疑问。
这是 html:
<ul data-bind="template: { name: 'attachements-template', foreach: attachements }">
</ul>
<script type="text/html" id="attachements-template">
<li>
<span data-bind="text: FileName"></span>
<img class="file-type-icon" data-bind="attr:{src: ImagePath}"/>
</li>
</script>
这是模型:
var Attachement = function () {
var self = this;
this.Id = ko.observable();
this.FileName = ko.observable();
self.ImagePath = ko.computed(function () {
return "images/" + getFileType(self.FileName);
});
};
var AttachementListModel = function () {
var self = this;
self.attachements = ko.observableArray([new Attachement()]);
...
};
getFileType
只是一些 js 函数,它返回一些字符串,如“image”或“document”:
我相信这是一个问题,这给了我“Uncaught TypeError: Object function observable() ...”
是否可以通过外部函数计算变量?
但是,我也遇到了没有这个功能的问题。
self.ImagePath = ko.computed(function () {
return "images/" + self.FileName;
});
以下是我将数据加载到 attachmentListModel.attachements
中的方法:
$(document).ready(function () {
attachementListModel = new AttachementListModel();
ko.applyBindings(attachementListModel, document.getElementById("@uniqueAttachementsPanelId"));
// get all attachements for given business entity data
$.ajax({
url: "/api/attachement",
contentType: "text/json",
dataType: "json",
type: "GET",
data: { businessEntityType: "type", id: 1 },
success: function (data) {
attachementListModel.attachements(data);
},
error: function (data) {
alert("Error");
}
});
})
在这种情况下(没有外部函数)t 给出错误:无法解析绑定(bind)。 ...(匿名函数)。
所以,我不知道问题是否出在 attachmentListModel.attachements(data);
部分(发生了一些映射),或者问题出在代码的其他部分。
最佳答案
您只需在计算出的 ImagePath
中使用 self.FileName()
解开您的 FileName
可观察对象:
self.ImagePath = ko.computed(function () {
return "images/" + getFileType(self.FileName());
});
但是,您的fileName
可能未定义
,因为getFileType
在您设置FileName
之前被调用。
您可以使您的计算延迟,这样它只会在您实际执行时调用您的getFileType
使用ImagePath
:
self.ImagePath = ko.computed(
function () { return "images/" + getFileType(self.FileName()); } ,
self,
{ deferEvaluation: true }
);
第二个问题是 attachmentListModel.attachements(data);
没有自动发生映射。您需要手动执行此操作或使用映射插件。
要手动执行此操作,您将需要类似以下内容:
success: function (data) {
ko.utils.arrayMap(data, function(item) {
var attachment = new Attachement();
attachment.Id(item.Id);
attachment.FileName(item.FileName);
attachementListModel.attachements.push(attachment);
});
},
关于javascript - 在映射过程中使用外部函数计算 knockout 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19809900/