【问题标题】:Get notified when Objective-C dom updates are ready initiated from webview当从 webview 启动 Objective-C dom 更新时收到通知
【发布时间】:2010-05-16 17:45:40
【问题描述】:

我通过DOMElement 对象以编程方式更新WebKit webview 上的DOM - 对于复杂的UI,我添加的任何元素通常都有一个Javascript 组件。这就需要在更新完成时得到通知——有没有这样的事件?我知道常规 div 不会触发 onloadonready 事件,对吗?我的另一个假设(可能完全错误)是 DOMElement 更新不是同步的,所以我不能做这样的事情并确信它会在 DOM 中实际遇到标签:

DOMElement *displayNameLabel = [document createElement:@"div"];
[displayNameLabel setAttribute:@"class" value:@"user-display-name"];
[displayNameLabel setTextContent:currentAvatar.avatarData.displayName];
[[document getElementById:@"user-card-content"] appendChild:displayNameLabel];
id win = [webView windowScriptObject];
[win evaluateWebScript:@"javascriptInstantiateLabel()"];

这是真的吗?

我已经在 html 正文中使用了 jQuery,所以我不介意通过“live”订阅特定类的事件集。我想我也许可以做类似的事情:

$(".some-class-to-be-added-later").live( "ready", function(){
    // Instantiate some fantastic Javascript here for .some-class
});

但到目前为止还没有经历过任何快乐。当元素在 DOM 中时,是否有任何方式(objective-c,因为我没有以编程方式触发 Javascript 后加载或 Javascript)来获得通知?

编辑:根据 Anurag 的回答,这是我想出的代码(有效):

    function onButtonPanelChange() {
        console.log( "Button panel subtree modified", 7 );
        $(".panel-button").each( function(){
            console.log( "Button found " + $(this).attr( "class" ), 7 );
            if( !$(this).hasClass( "processed" ) ){ 
                $("#bottom-button-panel").unbind( "DOMSubtreeModified" );
                if( $(this).hasClass( "chat" ) ){
                    console.log( "Found chat button, instantiating", 7);
                    var chat_button = new Button( $(this), chat_button_def );
                    $(this).addClass( "processed" );
                }
                else if( $(this).hasClass( "get" ) ){
                    var chat_button = new Button( $(this), get_button_def );
                    $(this).addClass( "processed" );
                }
                $("#bottom-button-panel").bind( "DOMSubtreeModified", onButtonPanelChange );
                console.log( "Done with button change, rebinding", 7 );
            }
        });
    }
    $(document).ready( function(){
        $("#bottom-button-panel").bind( "DOMSubtreeModified", onButtonPanelChange);
    });

请注意,您需要取消绑定该事件,因为每个后续更改都会触发另一个事件,一个,另一个,另一个。

【问题讨论】:

    标签: javascript objective-c dom webkit jquery-events


    【解决方案1】:

    查看一个小时前提出的类似问题 - Is there a JavaScript/jQuery DOM change listener?

    要监听元素的变化,请使用以下内容:

    $("#someDiv").bind("DOMSubtreeModified", function() {
        alert("tree changed");
    });
    

    我没有通过 Objective-C 编写 DOM 脚本,所以不知道是否有办法使用 Objective-C 包装器订阅 DOM 事件。

    DOMSubtreeModified modified 事件适用于 iPhone。刚刚用this example 测试过。

    【讨论】:

    • 确实不错。这太棒了——我会试试看。
    猜你喜欢
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2017-01-27
    • 2017-11-20
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多