Reputation: 2912
I started reimplementing some js code with knockout.js. I have a singleton with some functions in it:
Dps = {
someFunction: function() {
this.anotherFunction();
},
anotherFunction: function() {
console.log('tehee');
}
}
Now there are also some bindings which calls functions of this singleton:
<input type="text" data-bind="event: { change: Dps.someFunction }" />
The annoying thing is, that the context in the called function is the event, so I can't call this.anotherFunction()
Is there a nice way to get rid of this?
PS: I'm aware that I could do something like Dps.someFunction() instead, but this is not nice in my opinion.
Upvotes: 0
Views: 314
Reputation: 5224
Your functions behaves as "static"
So either you have to do Dps.anotherFunction but you don't want that, but I don't see why tbh.
You can also call ko.applyBindings(Dps) and then your code would work fine. However I guess that's not what you're looking for either. Probably you have another viewmodel all together, no?
Another solution is to make Dps into a function which you instantiate
On jsfiddle: http://jsfiddle.net/PrbqZ/
<input type="text" data-bind="event: { change: myDps.someFunction }" />
var Dps = function() {
var self = this;
this.someFunction = function() {
self.anotherFunction();
};
this.anotherFunction = function() {
console.log('tehee');
};
}
var myDps = new Dps();
//normally use dom ready, just simulating here
setTimeout(function(){
ko.applyBindings();
}, 500)
Upvotes: 1
Reputation: 140234
data-bind="event: { change: Dps.someFunction.bind(Dps) }"
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Upvotes: 1