Reputation: 49261
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.
Upvotes: 1
Views: 447
Reputation: 1735
Try this
define(['knockout'],
function(ko) {
var createVM = function() {
var vm = {
activate: activate,
companyId: null;
company: ko.observable({})
}
return vm;
};
. var vm = createVM(); return vm;
function activate(companyId) {
vm.companyId = companyId;
//get company data then
vm.company(data);
}
}
Upvotes: 1
Reputation: 4269
You should re-factor it this way:
define(['knockout'],
function(ko) {
var vm = function() {
this.companyId = null;
this.company = ko.observable({});
};
vm.prototype.activate = function (companyId) {
this.companyId = companyId;
//get company data then
this.company(data);
};
return vm;
}
Upvotes: 1
Reputation: 8620
Try it this way:
var vm = function() {
this.activate = activate;
this.companyId = null;
this.company = ko.observable({});
};
Without any qualifiers to the assignment, those keywords are being assigned to global variables.
However, if this module is already in use by code that you can't easily modify, then you may have a problem, since anything referring to vm would need to know it's a function they need to call.
Upvotes: 1