拦截Famo.us的链接点击

Intercepting link clicks in Famo.us

本文关键字:链接 Famo us 拦截      更新时间:2023-09-26

假设有一个使用Famo声明的曲面。包含标记内容的Us:

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

是否有一个(简单的)方法来拦截点击事件?

附加:除了拦截点击,如何传递点击事件,使默认处理程序也做它的工作?

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

完整代码如下: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实用程序加载它们在famous.

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事件仍然在表面触发。您可以通过查看控制台日志查看。

你不能直接在表面上打开一个新的链接,但是你可以添加一些像IFrameSurface: Famo这样的东西。我们IframeSurface

正如ainnorest所暗示的那样,您很可能希望为界面的单击添加一个事件处理程序:

this.mySurface.on('click', function(e) {
    // Bonus: on click do the standard redirect on main window
    // or redirect of iFrame control
    window.location = "http://famo.us";
});

,然后代替内容中的href,你只需要文本'This is a link'作为处理程序提供通常预期的逻辑,但通过拦截。

如果你出于某种原因需要将它们作为"链接",你可以尝试在href中添加一个散列,以避免实际上通过默认行为进行导航。

作为一种选择,因为我们在javascript中工作,你可以尝试这样做:

使用javascript拦截所有文档链接点击