javascriptc#requirejsamddurandal-2.0

AMD instance module that uses its own constructor - Durandal


In a Durandal app with MVC + Web API back-end I have the following C# class:

public class ProductFilter
{
    public string Name { get; set; }
    public List<ProductFilter> DependentFilters { get; set; }
}

I have a front-end instance model filter.js that I want to map to this class. It currently looks like this:

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));
        }); 
    };
});

As you can see, the C# class has a collection of its own type, and I need to replicate that structure on the Durandal model. In the example above I've tried injecting the filter.js module into itself, but RequireJs doesn't seem to like that as the filter variable is always undefined.

My problem probably stems from a lack of RequireJs or AMD modules knowledge, but how can I actually call the constructor of the current module within itself?


Solution

  • Define the function so that it has an name, and just call it from itself. You can then return the function by referring to it by name:

    define(function () {
        function filter (data) {
            // ... same as in your question ...
            $.each(ko.unwrap(data.dependentFilters || []), function () {
                self.dependentFilters.push(new filter(this));
            }); 
        };
    
        return filter;
    });