在具有 MVC + Web API 后端的 Durandal 应用程序中,我有以下 C#
类:
public class ProductFilter
{
public string Name { get; set; }
public List<ProductFilter> DependentFilters { get; set; }
}
我有一个前端实例模型 filter.js
我想映射到这个类。目前看起来像这样:
define(["models/filter"], function (filter) {
return function (data) {
var self = this;
data = data || {};
self.name = ko.observable(ko.unwrap(data.name || ""));
self.dependentFilters = ko.observableArray();
$.each(ko.unwrap(data.dependentFilters || []), function () {
// ---> 'filter' is undefined, so I cannot call new filter(..)
self.dependentFilters.push(new filter(this));
});
};
});
如您所见,C#
类有一个自己类型的集合,我需要在 Durandal 模型上复制该结构。在上面的示例中,我尝试将 filter.js
模块注入(inject)到自身中,但是 RequireJs
似乎不喜欢那样作为 filter
变量总是 undefined
。
我的问题可能源于缺乏 RequireJs
或 AMD
模块知识,但我如何才能真正调用当前模块本身的构造函数?
最佳答案
定义函数,让它有一个名字,然后从它自己调用它。然后,您可以通过按名称引用函数来返回该函数:
define(function () {
function filter (data) {
// ... same as in your question ...
$.each(ko.unwrap(data.dependentFilters || []), function () {
self.dependentFilters.push(new filter(this));
});
};
return filter;
});
关于javascript - 使用自己的构造函数的 AMD 实例模块 - Durandal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32741430/