How do I convert an AMD module from a singleton to an instance?
- by Jamie Ide
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.