Recently in the use of KNOCKOUTJS development mobile end, the first mobile end of the front-end, encountered a lot of problems, now talk about creating a custom bindings (do not know how to translate the word good, simply in English).
In the process of development, initially did not consider the click event on the mobile side there will be a delay of 300ms problem (in fact, I also know the problem at the beginning, I intend to finish the function before dealing with this problem). After you found the Click event User experience is too bad, and then replaced by Touchstart event, but found that Touchstart event in the user sliding page easily triggered by mistake, so find a tap event plug-in Https://github.com/pukhalski/tap.
So I need to replace the data-bind= "CLICK:FN" in the page with data-bind= "Event:{tap:fn}", too many places to replace, and this is not good to write, you can not directly replace click to tap it? , so I thought of Knockoutjs's custom bindings, which, according to the official documentation, added tapbinding:
Ko.bindingHandlers.tap = {
init:function (element, Valueaccessor, allbindings, ViewModel, BindingContext) {
$ (Element). On ("Tap", function () {
valueaccessor () (ViewModel, $ (this));
});
}
}
As a result, the data-bind= "TAP:FN" on the page can function correctly.
If the model is like this:
var model = {
Fn:function (data,event) {
///www.xiaoboy.com original ...
}
}
So I wondered if I could do exactly the same thing as the click-Pass (in fact, my business needs have been met)? Look at the source code of Knockoutjs, see a similar implementation of Click, there is a piece of code:
Function makeeventhandlershortcut (EventName) { ko.bindinghandlers[eventname] = { ' init ' : function (element, Valueaccessor, allbindings, viewmodel, bindingcontext) { var newValueAccessor = function () { var result
= {}; result[
Eventname] = valueaccessor (); return
Result
}; return ko.bindinghandlers[' event ' [' Init '].call (this, element, newvalueaccessor, allbindings, viewmodel,
BindingContext); }  }}
As you can see from this function, data-bind= "CLICK:FN" is actually a shortcut to data-bind= "Event:{click:fn}", and if you need to add a tap shortcut, You only need to give the Makeeventhandlershortcut method incoming tap parameters, the final tap of the custom binding implementation method is as follows:
Ko.bindingHandlers.tap = {
init:function (element, Valueaccessor, Allbindingsaccessor, ViewModel, BindingContext {
var newvalueaccessor = function () {return
{
tap:valueaccessor ()
};
};
Return ko.bindinghandlers[' event ' [' Init '].call (this, element, Newvalueaccessor, allbindings, ViewModel, BindingContext);
}
};
At this point, tap and click Pass the same parameters.