点击绑定的启用条件 [英] Enable condition for click binding
本文介绍了点击绑定的启用条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法为点击绑定指定启用条件?例如,如果我有以下内容:
Is there any way to specify an enable condition for the click binding? For example if I have the following:
<div data-bind="click: toggleDialog">Click Me</div>
如果出现指定条件,我希望能够禁用点击,从而达到以下效果:
I'd like to be able to disable clicking if a specified condition occurs so something to the effect of:
<div data-bind="click: toggleDialog, enableClick: myName() === 'John'">Click Me</div>
我想也许自定义绑定可以解决这个问题,但不太确定如何去做.
I'm thinking maybe a custom binding would work for this, but not quite exactly sure how to go about doing it.
推荐答案
你可以使用我为锚做的这个方法
You can use this approach that I did for anchors
(function() {
//First make KO able to disable clicks on Anchors
var orgClickInit = ko.bindingHandlers.click.init;
ko.bindingHandlers.click.init = function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
if(element.tagName === "DIV" && allBindingsAccessor().enable != null) {
var disabled = ko.computed({
read: function() {
return ko.utils.unwrapObservable(allBindingsAccessor().enable) === false;
},
disposeWhenNodeIsRemoved: element
});
ko.applyBindingsToNode(element, { css: { disabled: disabled} });
var handler = valueAccessor();
valueAccessor = function() {
return function() {
if(ko.utils.unwrapObservable(allBindingsAccessor().enable)) {
handler.apply(this, arguments);
}
}
};
}
orgClickInit.apply(this, arguments);
};
})();
更多详情:https://github.com/AndersMalmgren/Knockout.BindingConventions/wiki/Button-约定
这篇关于点击绑定的启用条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文