您的位置:首页 > Web前端 > JavaScript

webkit的js对象扩展(一)——binding方式创建自定义对象(单实例)

2011-12-07 20:19 686 查看
通过binding方式

要扩展一个全局JS对象除了要为webkit添加这个对象的头文件和cpp文件外,还需要为这个对象写一个idl文件以便webkit自动生成相应的代码;另外,还需要修改DOMWindow.*以便把新对象注册上去。下面以MyObject对象为例介绍具体步骤。

WebCore/page/

1.添加MyObject.h文件

view
plain

#ifndef MyObject_h  

#define MyObject_h  

#include <wtf/PassRefPtr.h>  

#include <wtf/RefCounted.h>  

#include <wtf/RefPtr.h>  

  

namespace WebCore {  

  

class Frame;  

class String;  

  

class MyObject : public RefCounted<MyObject> {  

  

    public:  

        static PassRefPtr<MyObject> create(Frame* frame)  

        {  

            return adoptRef(new MyObject(frame));  

        }  

  

        ~MyObject();  

  

        void disconnectFrame();  

        Frame* frame() const { return m_frame; }  

  

        String description() const;  

    private:  

        MyObject(Frame*);  

        Frame* m_frame;  

};  

}  

  

#endif  

2.添加MyObject.cpp文件

view
plain

#include "MyObject.h"  

  

#include "PlatformString.h"  

  

namespace WebCore {  

  

    MyObject::MyObject(Frame* frame)  

        : m_frame(frame)  

    {  

    }  

  

    MyObject::~MyObject()  

    {  

        disconnectFrame();  

    }  

  

    void MyObject::disconnectFrame()  

    {  

        m_frame = 0;  

    }  

  

    String MyObject::description() const    //对象的属性  

    {  

        return "Hello World!";  

    }  

}  

3.添加MyObject.idl文件

view
plain

module window {  

    interface MyObject {  

        readonly attribute DOMString description;  

    };  

}  

4.修改DOMWindow.h文件

添加如下声明:

view
plain

public:  

    MyObject* myObject() const;  

    MyObject* optionalMyObject() const { return m_myObject.get(); }  

private:  

    mutable RefPtr<MyObject> m_myObject;  

5.修改DOMWindow.cpp文件

添加接口实现

view
plain

MyObject* DOMWindow::myObject() const  

{  

    if (!m_myObject)  

        m_myObject = MyObject::create(m_frame);  

    return m_myObject.get();  

}  

修改部分函数实现

void
DOMWindow::clear()函数中添加:

view
plain

if (m_myObject)  

    m_myObject->disconnectFrame();  

m_myObject = 0;  

6.修改DOMWindow.idl文件

添加:

view
plain

attribute [Replaceable] MyObject MyObject;  

7.修改CMakeLists.txt

将MyObject.cpp、MyObject.idl加入编译。

OK。以上步骤就添加了一个自定义的全局对象。这是单实例的,有时间了再把多实例的过程写下,也就是可以new了。

小弟新手,有问题请大家多多指教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binding webkit 扩展