[英]Knockout.js event context
我开始用knockout.js重新实现一些js代码。 我有一个包含一些函数的单例:
Dps = {
someFunction: function() {
this.anotherFunction();
},
anotherFunction: function() {
console.log('tehee');
}
}
现在还有一些绑定调用这个单例的函数:
<input type="text" data-bind="event: { change: Dps.someFunction }" />
令人讨厌的是,被调用函数中的上下文是事件,所以我不能调用this.anotherFunction()
有没有一个很好的方法摆脱这个?
PS:我知道我可以做一些类似Dps.someFunction()的事情,但在我看来这并不好。
data-bind="event: { change: Dps.someFunction.bind(Dps) }"
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
你的函数表现为“静态”
所以要么你必须做Dps.anotherFunction但你不想要那个,但我不明白为什么tbh。
你也可以调用ko.applyBindings(Dps)然后你的代码就可以了。 但是我猜这不是你想要的。 可能你有另一个视图模型,不是吗?
另一种解决方案是将Dps转换为您实例化的函数
在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.