I have a HTML element bound to one of observables in my view model that is build with John Resig’s simple javascript inheritance.
<div data-bind="with: selectedItem()">
...
<div data-bind="click: $root.save">Save changes</div>
...
</div>
My ViewModel looks like this.
var ViewModel = Class.extend({
init: function(type){
this.type = type;
this.selectedItem = ko.observable({name: "My name"});
},
save: function(data){
alert(this.type);
}
});
The “this” in the ViewModel#save references to “selectedItem()”.
In other words, “this” references to “data” passed into the function.
How can I access to the instance of ViewModel, instead?
Edited
The intention here is to inherit functions from ViewModel. I would like to access “this.type” as “first” and “second” respectively.
var FirstViewModel = ViewModel.extend({
init : function() {
this._super('first');
}
});
var SecondViewModel = ViewModel.extend({
init : function() {
this._super('second');
}
});
Check out this answer, and the one below it:
https://stackoverflow.com/a/346044/1388165
You’re hitting one of the interesting parts of Javascript, where “this” refers to the object that is calling the function, not the parent object of the function being called. This can be dealt with by using closures, such as the common that = this pattern in the example below.
If you are going to be spending a lot of time with Javascript, I’d strongly recommend Douglas Crockford’s book “Javascript: The Good Parts”, it will make you aware of a lot of things like this. I’d also recommend watching Crockford’s talks on YouTube (there are many).
Edit with example: