1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryの自作ウィジェットで「Uncaught TypeError: Cannot read property 'XXX' of undefined」となる問題を克服しました

Last updated at Posted at 2015-08-22

jQueryで自作ウィジェットを作成してみたところ、以下のエラーに遭遇しました。DOM?に格納されているウィジェットのインスタンス名が間違えていたようです。

エラー
Uncaught TypeError: Cannot read property 'メソッド名' of undefined

環境

  • CentOS 6.6
  • jQuery 1.8.3/1.9.1/1.10.2/1.11.3

問題のコード

main.js
(function ($) {
    "use strict";

    $(function () {
        var obj1;
        $("#myWidget1").myWidget();
        obj1 = $("#myWidget1").data("jqWidget"); // ここが問題
        obj1.setContent("hello myWidget1");
    });
})(jQuery);
jqWidget.js
(function($) {
    "use strict";

    $.widget("ui.jqWidget", {
        options: {
            content: "hoge"
        },

        _init: function () {
            this._update();
        },

        _update: function () {
            var opts = this.options;
            var elm = this.element;
            elm.html(opts.content);
        },

        setContent: function (str) {
            this.options.content = str;
            this._update();
        }
    });
})(jQuery);
main.html
<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>jQuery Widget example</title>
    <link rel="stylesheet" href="vendor/jquery-ui-1.11.4.css" type="text/css" media="screen">
</head>
<body>
<div id="myWidget1"></div>
<script type="application/javascript" src="vendor/jquery-1.8.3.js"></script>
<script type="application/javascript" src="vendor/jquery-ui-1.11.4.js"></script>
<script type="application/javascript" src="js/jqWidget.js"></script>
<script type="application/javascript" src="js/main.js"></script>
</body>
</html>

修正

main.js
(function ($) {
    "use strict";

    $(function () {
        var obj1;
        $("#myWidget1").myWidget();
        obj1 = $("#myWidget1").data("ui-jqWidget"); // ここを修正
        obj1.setContent("hello myWidget1");
    });
})(jQuery);

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?