请帮助我尝试理解小工具厂中setOptions
和setOption
的概念。
在下面的代码中,我认为如果我更改了选项颜色this.options.green += 1;
,那么_setOption将会因为options属性发生更改而触发。
当我阅读文档但是我正在努力的时候,请你帮我理解setOptions和setOption的概念。谢谢你的帮助。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Widget - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!--<link rel="stylesheet" href="/resources/demos/style.css">-->
<style>
.custom-colorize {
font-size: 20px;
position: relative;
width: 75px;
height: 75px;
}
.custom-colorize-changer {
font-size: 10px;
position: absolute;
right: 0;
bottom: 0;
}
</style>
<script>
$(function () {
$.widget("custom.colorize", {
// default options
options: {
red: 255,
green: 0,
blue: 0,
},
// the constructor
_create: function () {
this.element.addClass("custom-colorize");
this.changer = $("<button>", {text: "change", "class": "custom-colorize-changer"}).appendTo(this.element);
this._on(this.changer, {click: "editMyColour"});
this._drawShape();
},
editMyColour: function (event) {
this.options.green += 1;
//alert('test');
//this._drawShape();
},
_drawShape: function () {
this.element.css("background-color", "rgb(" + this.options.red + "," + this.options.green + "," + this.options.blue + ")");
//this._trigger("change");
},
// _setOptions is called with a hash of all options that are changing
// always refresh when changing options
_setOptions: function () {
// _super and _superApply handle keeping the right this-context
this._superApply(arguments);
this._drawShape();
},
// _setOption is called for each individual option that is changing
_setOption: function (key, value) {
this._super(key, value);
}
});
// initialize with default options
$("#my-widget1").colorize();
// click to set options after initialization
$("#black").click(function () {
//$(":custom-colorize").colorize("option", {
$('#my-widget1').colorize("option",{
red: 0,
green: 0,
blue: 0
});
});
});
</script>
</head>
<body>
<div>
<div id="my-widget1">color me</div>
<button id="disable">Toggle disabled option</button>
<button id="black">Go black</button>
</div>
</body>
</html>
答案 0 :(得分:3)
this.options
正在直接访问选项对象。它只是一个对象 - 没有人在倾听它的变化。要做你认为会发生的事情,你可以拨打_setOption
,就像this._setOption('green', this.options.green + 1);
一样。在外部设置选项时会调用_setOption
函数,例如$('#my-widget1').colorize("option", "red", 0});