How do I convert an AMD module from a singleton to an instance?

Posted by Jamie Ide on Stack Overflow See other posts from Stack Overflow or by Jamie Ide
Published on 2013-10-28T17:24:37Z Indexed on 2013/10/29 21:55 UTC
Read the original article Hit count: 251

Filed under:
|
|

I'm trying to convert a working Durandal view model module from a singleton to an instance. The original working version followed this pattern:

define(['knockout'],
function(ko) {

    var vm = {
        activate: activate,
        companyId: null;
        company: ko.observable({})
    };

    return vm;

    function activate(companyId) {
        vm.companyId = companyId;
        //get company data then
        vm.company(data);
    }
}

The new version exports a function so that I get a new instance on every request...

define(['knockout'],
function(ko) {

    var vm = function() {
        activate = activate;
        companyId = null;
        company = ko.observable({});
    };

    return vm;

    function activate(companyId) {
        vm.companyId = companyId;
        //get company data then
        vm.company(data);
    }
}

The error I'm getting is "object function () [...function signature...] has no method company on the line vm.company(data);. What am I doing wrong? Why can I set the property but can't access the knockout observable? How should I refactor the original code so that I get a new instance on every request?


My efforts to simplify the code for this question hid the actual problem. My real code was using Q promises and calling two methods with Q.All. Since Q is in the global namespace, it couldn't resolve my viewmodel after converting to a function. Passing the view model to the methods called by Q resolved the problem.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about knockout.js