Reputation: 614
Is there any way to add a new method to an already defined Model e.g.
var MyModel = function() {
var self = this;
self.method1 = function () {
return true;
}
self.method2 = function () {
return true;
}
};
viewModel = new MyModel ();
ko.applyBindings(viewModel);
This gives me access to viewModel.method1()
and viewModel.method2()
but I want to be able to add a new method later on in the file that I can access in the same way e.g.
viewModel.extend = function() {
self.method3 = function () {
return true;
}
}
And now I would have access to viewModel.method1()
, viewModel.method2()
and viewModel.method3()
Any ideas?
Thanks
Upvotes: 0
Views: 40
Reputation: 78585
You can define one using a prototype:
MyModel.prototype.method3 = function() {
var self = this; // Reference to instance of MyModel
var m1 = self.method1();
var m2 = self.method2();
return true;
};
In your example:
var MyModel = function() {
var self = this;
self.method1 = function () {
return true;
}
self.method2 = function () {
return true;
}
};
viewModel = new MyModel ();
ko.applyBindings(viewModel);
MyModel.prototype.method3 = function() {
return true;
};
console.log(viewModel.method3());
Upvotes: 1