我正在尝试为我的应用程序创建一个基本视图模型,但我正在努力访问基本视图模型的上下文。
这是我的基本视图模型:
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;
});
我使用这个不工作的东西的一个例子是:
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;
});
使用populateCollection
.
confirmDelete
也可以在模板中正确绑定,这可能是由于不需要上下文但deleteItem
需要上下文以便它可以访问items
和调用remove
它。
我如何正确地访问
this
它的上下文,baseViewModel
以便我可以使用这种模式在我的方法中轻松地引用它?
非常感谢