knockout.js和禁用锚标签

时间:2012-05-30 16:12:46

标签: knockout.js anchor javascript

如何使用此自定义绑定禁用和启用锚标记。它适用于输入元素,但锚标记只是改变了CSS,而不是禁用。

<a href="link" data-bind="myDisabled: !enabled()"/>

ko.bindingHandlers.myDisabled = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        ko.bindingHandlers.css.update(element, function() {return { disabled: value }; });
        ko.bindingHandlers.disable.update(element, valueAccessor);
    }
};

4 个答案:

答案 0 :(得分:11)

您需要在绑定处理程序中捕获click事件。

<强> HTML

<a href="link" data-bind="disableClick: !enabled()">test</a>
<br/><br/><br/>
<input type="checkbox" data-bind="checked: enabled"> enabled ​

<强>的JavaScript

ko.bindingHandlers.disableClick = {
    init: function (element, valueAccessor) {

        $(element).click(function(evt) {
            if(valueAccessor())
                evt.preventDefault();
        });

    },

    update: function(element, valueAccessor) {        
        var value = ko.utils.unwrapObservable(valueAccessor());
        ko.bindingHandlers.css.update(element, function() {return { disabled_anchor: value }; });
    }
};

ko.applyBindings({ enabled: ko.observable(false)});

这是一个有效的例子:

http://jsfiddle.net/kp74u/54/

UPDATE 1 :如果您需要阻止在附加了敲除绑定处理程序后绑定的其他事件处理程序,则需要将stopImmediatePropagationpreventDefault一起添加到事件处理程序中。

示例:http://jsfiddle.net/kp74u/55/

UPDATE 2 :如果要禁用所有事件处理程序(以及在绑定处理程序之前附加的单击事件处理程序,则需要'破解'jquery事件数组)。请注意,这可能不适用于其他版本的jquery(示例使用1.7):

ko.bindingHandlers.disableClick = {
    init: function(element, valueAccessor) {

        $(element).click(function(evt) {
            alert('test before');
        });

        $(element).click(function(evt) {
            if (valueAccessor()) {
                evt.preventDefault();
                evt.stopImmediatePropagation();
            }
        });

        //begin of 'hack' to move our 'disable' event handler to top of the stack
        var events = $.data(element, "events");
        console.log(events);
        var handlers = events['click'];

        if (handlers.length == 1) {
            return;
        }

        handlers.splice(0, 0, handlers.pop());
        //end of 'hack' to move our 'disable' event handler to top of the stack


        $(element).click(function(evt) {
            alert('test after');
        });
    },

    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        ko.bindingHandlers.css.update(element, function() {
            return {
                disabled_anchor: value
            };
        });
    }
};

示例:http://jsfiddle.net/nickolsky/kp74u/40/

更新3 :正如那里提到的那样(suggested edit by FIR55TORM,抱歉无法批准这种完全正确的编辑,因为我来不及审核):如果您使用的是jQuery 1.10。 x,你需要添加一个下划线来访问'data'对象,如下所示:

var events = $._data(element, "events"); 

jQuery 1.10.x的修改小提琴:http://jsfiddle.net/nickolsky/kp74u/41/

答案 1 :(得分:1)

我在寻找一种方法时找到了这个答案,但我不喜欢这种方法,所以我自己做了

var orgClickInit = ko.bindingHandlers.click.init;
ko.bindingHandlers.click.init = function (element, valueAccessor, allBindingsAccessor, viewModel) {
    if (element.tagName === "A" && allBindingsAccessor().enable != null) {
        var disabled = ko.computed(function () {
            return ko.utils.unwrapObservable(allBindingsAccessor().enable) === false;
        });
        ko.applyBindingsToNode(element, { css: { disabled: disabled} });
        var handler = valueAccessor();
        valueAccessor = function () {
            return function () {
                if (ko.utils.unwrapObservable(allBindingsAccessor().enable)) {
                    handler.apply(this, arguments);
                }
            }
        };

    }
    orgClickInit(element, valueAccessor, allBindingsAccessor, viewModel);
};

它与本机点击无关并启用绑定(禁用绑定未实现) 小提琴(小提琴也使用我的约定配置库) http://jsfiddle.net/xCfQC/30/

答案 2 :(得分:0)

使用@Anders答案作为灵感,我想出了我自己的版本。允许在有或没有“点击”的情况下使用“启用”,“禁用”。还允许自定义禁用类,否则默认为“禁用”。

var koEnableUpdateOrig = ko.bindingHandlers.enable.update;
ko.bindingHandlers.enable.update = function (element, valueAccessor, allBindings) {
    // call original enable update
    var result = koEnableUpdateOrig.apply(this, arguments);
    var enabled = ko.unwrap(valueAccessor());

    // get and apply disabled class
    var disabledClass = "disabled";
    if (allBindings)
        disabledClass = allBindings().disabledClass || "disabled";
    if (enabled) {
        $(element).removeClass(disabledClass);
        if (element.tagName === "A")
            $(element).off("click.koEnableUpdate");
    }
    else {
        $(element).addClass(disabledClass);
        if (element.tagName === "A")
            $(element).on("click.koEnableUpdate", function (e) { e.preventDefault(); });
    }

    return result;
};
ko.bindingHandlers.disable.update = function (element, valueAccessor, allBindings) {
    // call enable with the reverse value
    // the original knockout disable does this, but does not pass the allBindings
    ko.bindingHandlers.enable.update(element, function () {
        return !ko.unwrap(valueAccessor())
    }, allBindings);
};

var koClickInitOrig = ko.bindingHandlers.click.init;
ko.bindingHandlers.click.init = function (element, valueAccessor, allBindings) {
    // wrap click function with enable/disable check
    var valueAccessorOrig = valueAccessor();
    valueAccessor = function () {
        return function () {
            if (ko.unwrap(allBindings().enable) ||
                (allBindings().disable == null || !ko.unwrap(allBindings().disable))) {
                valueAccessorOrig.apply(this, arguments);
            }
        }
    };

    // apply wrapped click to original click init
    koClickInitOrig.apply(this, arguments);
};

答案 3 :(得分:0)

这是我的方法:

<强>的JavaScript

(function () {
  var originalDisableUpdate = ko.bindingHandlers.disable.update;

  ko.bindingHandlers.disable.update = function (element, valueAccessor) {
      if (element.tagName === 'A') {
        var
          value = ko.utils.unwrapObservable(valueAccessor()),
          disabled = 'disabled';

        if (value) {
          element.setAttribute(disabled, null);
        }
        else {
          element.removeAttribute(disabled);
        }
      }
      else {
        originalDisableUpdate(element, valueAccessor);
      }
  };
})();

<强> CSS

a[disabled] {
  pointer-events:none;
  cursor:default;
}