假设使用Famo.us声明了一个包含标记内容的表面:

this.mySurface = new Surface({
    size : this.options.targetSize,
    content : '<a href="http://famo.us">This is a link</a>',
});


有没有一种简便的方法来拦截click事件?

奖励:除了拦截点击之外,如何传递点击事件,以便默认处理程序也能完成其工作?

最佳答案

有几种方法可以处理事件停止。我认为这是一个适合您的解决方案。当然,以这种方式加载页面或链接有其自身的警告,我们不会在这里深入探讨。

这是完整的代码:Example on jsFiddle

首先,我们跟踪目标表面内的点击,并调用该函数以检查它是否为链接。如果单击链接,我们将发出一个传递目标href的事件。

this.mySurface.clickNullifier = function (e) {
    if (e.target && e.target.nodeName == 'A' && e.target.href) {
        this.mySurface.emit('href-clicked', { data: { href: e.target.href } })
        return false;
    }
}.bind(this);

this.mySurface.on('deploy', function () {
    // sets up the click function on the surface DOM object
    this._currentTarget.onclick = this.clickNullifier;
});


现在已经跟踪了表面点击,我们将捕获所有被拦截的点击并将其加载到iFrame中,或者如果本地链接使用著名的loadURL实用程序将其加载。

this.mySurface.on('href-clicked', function (event) {
    console.log(event.data);
    // handle your code for the iframe
    // not always doable in the case of 'X-Frame-Options' to 'SAMEORIGIN'
    loadIframe.call(this, event.data.href);

    // or loadURL like here. Needs CORS open on the href server if cross origin
    //Utility.loadURL(event.data.href, loadLink.bind(this));
}.bind(this));

function loadIframe(content) {
    this.backSurface.setContent('<iframe src="' + content + '" frameborder="0" height="100%" width="100%"></iframe>');
};


奖励:在上面的示例链接中,您将看到click事件仍然在表面上触发。您可以通过查看控制台日志来查看。

10-06 16:01
查看更多