Skip to content
AndersMalmgren edited this page Jan 18, 2013 · 8 revisions

All objects of type function can be bound to a button element.

<button data-name="save">Save</button>

The convention will also look for a function guard member on the ViewModel which by convention is prefixed with can

TestViewModel = function() {
    var self = this;
    this.save = function() {
        self.canSave(false);
    };
    this.canSave = ko.observable(true);    
};

http://jsfiddle.net/3Ajnj/

Anchors

Anchor support is not built in to the library because enable and disabling of anchors are not supported by KO, here is a way of doing it

(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) {
      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);  
    };
    
    //Second make the Convention library work with anchors
    ko.bindingConventions.conventionBinders.button.rules[0] = function (name, element, bindings, unwrapped, type) { 
        return (element.tagName === "BUTTON" || element.tagName === "A") && type === "function"; 
    };
})();

http://jsfiddle.net/xCfQC/4/

Clone this wiki locally