I am trying to make a base view model for my app but I am struggling with accessing the context of the base viewmodel.
Here is my base viewmodel:
define(["config", 'services/logger'], function (config, logger) {
'use strict';
var
app = require('durandal/app'),
baseViewModel = function () {
this.items = ko.observableArray();
this.title = ko.observable();
this.selectedItem = ko.observable();
};
baseViewModel.prototype = (function () {
var
populateCollection = function (initialData, model) {
var self = this;
if (_.isEmpty(self.items())) {
ko.utils.arrayForEach(initialData, function (item) {
// self here works for all extending modules such as users
self.items.push(new model(item));
});
}
},
deleteItem = function (item) {
// "this" here same as prototype gives me window object :(
// so removing never happes
this.items.remove(item);
logger.log(config.messages.userMessages.confirmDeleted(item.Name()), {}, '', true);
},
confirmDelete = function (item) {
var
userMessage = config.messages.userMessages.confirmDelete(item.Type(), item.Name()),
negation = config.confirmationModalOptions.negation,
affirmation = config.confirmationModalOptions.affirmation;
app.showMessage(userMessage, 'Deleting ' + item.Type(), [affirmation, negation]).then(
function (dialogResult) {
dialogResult === affirmation ? deleteItem(item) : false;
});
};
return {
populateCollection: populateCollection,
confirmDelete: confirmDelete,
deleteItem: deleteItem
}
})();
return baseViewModel;
});
and an example of where I am using this non-working thing is:
define(['services/logger', 'models/user', 'viewmodels/baseviewmodel', 'services/dataservice'], function (logger, user, baseviewmodel, dataservice) {
var
users = new baseviewmodel();
users.title('Users')
users.searchTerm = ko.observable().extend({ persist: users.title() + '-searchterm' });
users.activate = function () {
this.populateCollection(dataservice.getUsers, user.model);
}
return users;
});
Items do get populated correctly using populateCollection
.
confirmDelete
also gets bound correctly in the template which is probably due to not needing context
but the deleteItem
needs the context so it can access items
and call remove
on it.
How do I correctly access
this
as the context of thebaseViewModel
so I can easily refer to it in my methods with this pattern?
Many Thanks