在主干网中使用iframe实体作为区域

Using iframe body as Region in Backbone Marionette

本文关键字:实体 区域 iframe 主干网      更新时间:2023-09-26

我正试图在Backbone Marionette中使用iframe的主体作为Region。Marionette使用标准的jquery选择器来定义哪个元素是区域,如下所示:

App.addRegions( { main: "#main-region" } );

我希望我的区域是iframe的主体,通常我会发现它是这样的:

$('iframe').contents().find('body');

当试图把上面作为区域时,像这样:

App.addRegions( { main: $('iframe').contents().find('body') } );

引发以下错误:

Uncaught Error: Syntax error, unrecognized expression: iframe.contents() body
  Sizzle.error   jquery.js?body=1:4681
  tokenize       jquery.js?body=1:4742
  select         jquery.js?body=1:5114

我试着直接把选择器放进去:

App.addRegions( { main: "iframe.contents() body" } );

但它给了我完全相同的错误。


编辑:

还试图为它创建一个psuedo选择器:

$.expr[":"].contents = $.expr.createPseudo(function(selector) {
  return function(el) {
    var $el;
    $el = $(el);
    console.log($el.contents().find(selector));
    return $($el.contents().find(selector));
  };
});
// Usage: $('iframe:contents body');

它确实在函数本身中记录iframe的主体:

[body, prevObject: jQuery.fn.jQuery.init[1], context: iframe, selector: ".contents() body", constructor: function, init: function…]

但最终以某种方式返回iframe元素:

[iframe, prevObject: jQuery.fn.jQuery.init[1], context: document, selector: "iframe:contents(body)", constructor: function, init: function…]

所以,我需要的是一个选择器,它能够获得iframe的身体或其他可以与Marionette一起工作的东西。

有办法做到这一点吗?

不确定您是否已经找到了这个解决方案的答案,但您可以通过自己创建区域而不是依赖Marionette的内置选择器行为来轻松实现这一点:

1) 首先,您需要创建一个新的Region,并传入一个DOM元素作为el选项:

var iframeRegion = new Backbone.Marionette.Region({
    // Make sure you get the DOM object out of the jQuery object (eg. the .get() call)
    el: $('iframe').contents().find('body').get(0) 
});

2) 然后将实例添加到您的应用程序中,而不是使用选择器字符串:

App.addRegions({
    main: iframeRegion
});