In one of my viewmodels I have a function Control
that creates an objects later to be bound to the view:
(The code is only reproducing my viewmodel, therefore it may be incomplete or containing some mistakes. If you need more details please ask in a comment bellow. Since the example refers to durandaljs framework I cannot provide a JsFiddle.)
function Control ( value ) {
var self = this;
self.param = value;
self.param1 = ko.observable(value.text());
self.param2 = ko.computed(function() {
read: function(){
return getString(self.param.text()).StringValue();
},
write: function(newValue){
stringsArray.push(
{StringID: ko.observable(-1), StringValue: ko.observable(newValue)});
self.param.text(-1);
},
owner: self
});
self.param3 = ko.computed(function() {
return self.param2() + ' something_else';
});
self.param1.subscribe(function( newValue ) {
if ( newValue ) {
self.param3(newValue + 'text');
}
});
}
var controls = ko.observableArray([
new Control({id: 1, text: ko.observable(2)}),
new Control({id: 2, text: ko.observable(4)}),
new Control({id: 2, text: ko.observable(1)})
]);
var stringsArray = ko.observableArray([
{StringID: ko.observable(1), StringValue: ko.observable('aaa')},
{StringID: ko.observable(2), StringValue: ko.observable('bbb')}
{StringID: ko.observable(3), StringValue: ko.observable('ccc')}
{StringID: ko.observable(4), StringValue: ko.observable('ddd')}
{StringID: ko.observable(5), StringValue: ko.observable('eee')}
{StringID: ko.observable(6), StringValue: ko.observable('fff')}
]); // data retrieved from the database
var deactivate = function() {
controls.removeAll();
stringsArray.removeAll();
};
var vm = {
deactivate: deactivate,
controls: controls,
stringsArray: stringsArray
};
return vm;
function getString ( stringID ) {
for ( var i = 0; i < stringsArray().length; i++ ) {
if ( stringsArray()[i].StringID() === stringID ) {
return stringsArray()[i];
}
}
return undefined;
}
My problem is that the objects that are created from the function are scoped globally, therefore when I deactivate the viewmodel they still exist in memory.
How should I rewrite the function Control(value)
so the objects that it creates will have the viewmodel scope. They will only exist when the viewmodel is active and discarded when I remove them from the observableArray in the deactivate
method?