我正在尝试将Hammer.js和knockout.js结合起来,但似乎有些东西不起作用。
我使用了这个功能:
var events = ['tap', 'doubletap', 'hold', 'rotate',
'drag', 'dragstart', 'dragend', 'dragleft', 'dragright', 'dragup',
'dragdown', 'transform', 'transformstart',
'transformend', 'swipe', 'swipeleft', 'swiperight',
'swipeup', 'swipedown', 'pinch', 'pinchin', 'pinchout'];
ko.utils.arrayForEach(events, function (eventName) {
ko.bindingHandlers[eventName] = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var origParams = ko.utils.unwrapObservable(valueAccessor()),
params = typeof(origParams) == 'function' ? {handler: origParams} : origParams,
hammerObj = hammer(element, params.options),
args = params.delegate ? [eventName, params.delegate, params.handler] : [eventName, params.handler]
hammerObj.on.apply(hammerObj, args);
}
}
});
例如,我正在尝试为我在页面上的每个图像获取拖动事件,所以在我的HTML上我有:
<div class="row-fluid" data-bind="foreach: {data: picturesArray}">
<ul class="thumbnails" >
<li class="img-item" data-bind="
doubletap: img.doubletap.bind(img),
drag: img.drag.bind(img)">
<img class="one-img"
style="width: 100px; height: 100px;" data-bind="attr: { src: img.media.m }"/>
</li>
</ul>
</div>
但它不起作用。在我的JS文件中,绑定的methond没有调用。
答案 0 :(得分:5)
这是我如何解决它。
http://plnkr.co/edit/WJnPNsHQIKbbUu7oaD12?p=preview
的Javascript
var events = ['tap', 'doubletap', 'hold', 'rotate',
'drag', 'dragstart', 'dragend', 'dragleft', 'dragright', 'dragup',
'dragdown', 'transform', 'transformstart',
'transformend', 'swipe', 'swipeleft', 'swiperight',
'swipeup', 'swipedown', 'pinch', 'pinchin', 'pinchout'];
ko.utils.arrayForEach(events, function (eventName) {
ko.bindingHandlers[eventName] = {
update: function(element, valueAccessor){
var BindingContext = valueAccessor()[0];
var EventToFire = valueAccessor()[1];
var options = {
dragLockToAxis: true,
dragBlockHorizontal: true
};
var hammerTime = new Hammer(element, options);
hammerTime.on(eventName, function(ev){
//Fire the event with the item it was bound to.
EventToFire(BindingContext);
});
}
}
});
HTML
<div data-bind="foreach: Elements">
<!-- send yourself and the binding event to the "drag" handler -->
<div class="square" data-bind="drag: [$data, $parent.Drag]">
<div data-bind="text: Test"></div>
</div>
</div>
答案 1 :(得分:0)
这个问题的综合答案和Calling the method provided in HTML in Knockout custom bindinghandler :)
var events = [ 'tap', 'doubletap', 'hold', 'rotate',
'drag', 'dragstart', 'dragend', 'dragleft', 'dragright', 'dragup',
'dragdown', 'transform', 'transformstart',
'transformend', 'swipe', 'swipeleft', 'swiperight',
'swipeup', 'swipedown', 'pinch', 'pinchin', 'pinchout' ];
ko.utils.arrayForEach( events, function( eventName ) {
ko.bindingHandlers[eventName] = {
init: function( element, valueAccessor ) {
var hammer = new Hammer( element );
var value = valueAccessor();
hammer.on( eventName, function(e) {
value(e);
});
}
}
});