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);