Skip to content
einsteinhx edited this page Nov 21, 2013 · 9 revisions

#新的API设计

一段html代码片段

<ul id="test">
    <li>
        <ul id="submenu">
	    <li><a href="#sub">Sub-menu Item</a></li>
	    <li><a href="#sub">Sub-menu Item</a></li>
	    <li><a href="#sub">Sub-menu Item</a></li>
	    <li><a href="#sub">Sub-menu Item</a></li>
	    <li><a href="#sub">Sub-menu Item</a></li>
	    <li><a href="#sub">Sub-menu Item</a></li>
	</ul>
    </li>
    <li>Test 1</li>
    <li>Test 2</li>
    <li>Test 3</li>
    <li>Test 4</li>
</ul>

1. 简单绑定

对单个dom的事件绑定方法

var handler = function(e){
    console.log(e);
};

touch.on("#test", "tap", handler);
touch.trigger("#test", "tap");
touch.off("#test", "tap", handler);
var handler = function(e){
    console.log(e);
};

touch.on("#test", "tap swipeLeft swipeRight", handler);
touch.trigger("#test", "tap");
touch.off("#test", "tap swipeLeft swipeRight", handler);

2. 事件代理

var handler = function(e){
    console.log(e);
};

touch.on("#test", "tap", "> li", handler);
touch.trigger("#test > li", "tap");
touch.off("#test", "tap", "> li", handler);
var handler = function(e){
    console.log(e);
};

touch.on("#test", "tap swipeLeft swipeRight", "> li", handler);
touch.trigger("#test > li", "tap");
touch.off("#test", "tap swipeLeft swipeRight", "> li", handler);

3. mapEvent

var handler = function(e){console.log(e)};

touch.on("#test", {
    'tap' : handler,
    'swipeLeft' : handler,
    'swipeRight': handler,
}, '> li');
touch.trigger("#test > li", "swipeLeft");
touch.off("#test", "swipeLeft", "> li", handler);

与0.2.6及之前的touch.js兼容

  • 兼容原因

    0.2.6及之前的touch.js不支持事件代理机制,而新的touch.js通过手势识别,事件冒泡及原生的事件对象,提供事件代理机制和自定义事件的能力,从而极大提升性能。原有的stopPropagation会阻止原生事件冒泡,从而使手势识别失效,因此,需要手动删除/注释stopPropagation语句。麻烦各位根据自己项目的实际情况,选择性升级touch.js

  • 兼容方法

1.删除/注释所有绑定中的stopPropagation方法

touch.on('#rotation .target', 'touchstart', function(ev){
    ev.startRotate();
    ev.originEvent.preventDefault();
    //ev.originEvent.stopPropagation();      //注释掉或者删掉stopPropagation方法
});