2013
Apr
17

YUI 3 中有一个最基本的 Module 叫 Attribute,主要功能是存取变数值,例如我想要设定一个变数,那我可以使用 Y.Attribute 的功能,建立一个 Attribute Object, 用他来管理我的变数设定 。

Y.Attribute 可以在 new Object 时, Initialize 一些 attribute 进去。

Simple Attribute
  1. var GB = new Y.Attribute({
  2. "maxWidth": { value: "1000px"},
  3. "maxHeight": {value: "800px"}
  4. });
  5. console.log(GB.get("maxWidth"));// output 1000px
  6. GB.set("maxWidth", "900px");
  7. console.log(GB.get("maxWidth")); // output 900px

Attribute event : value change

YUI 3 的 attribute 还有个 event 的管理功能,当某一个变数的内容变更时,我可以指定它去触发某一个事件,例如上一个范例中的 maxWidth 被变更时,我可能会希望视窗的尺寸也跟著改变。

讲到 event ,就要先知道他的 event 名称,假设我定义一个 Attribute 变数名称为 attrName,则这个变数的内容变更时,它的 Event 名称为 「attrNameChange」,change 就是指变数被变更的意思,在 change 前面再加上 attribute 名称,就是他的 event 了。

为了让这个 Event 能够顺利触发,我们必须先帮它绑定 function,绑定方式就是使用 YUI on 来完成。

Bind attribute event 范例
  1. var A = new Y.Attribute({
  2. "attrName": {
  3. value: "test",
  4. writeOnce: false
  5. }
  6. });
  7. A.on("attrNameChange", function (e) {
  8. Y.log("Attribute name = " + e.attrName);
  9. Y.log("Original value = " + e.prevVal + ", New value = " + e.newVal);
  10. Y.log("event trigger" + e.data3); Y.log(e);}, {data3:2}
  11. );

最后再透过 AttributeObject.set(key, value); 去修改 attribute 内容,这样 YUI 就会自动去触 attrChange 的 event 而执行我们指定的 function 。

全部的程式范例

source code 范例
  1. <script>
  2. YUI().use("node", "lang", "base", "attribute", "attribute-observable", function (Y) {
  3.  
  4. var A = new Y.Attribute({
  5. "attrName": {
  6. value: "test",
  7. writeOnce: false
  8. }
  9. });
  10.  
  11. A.on("attrNameChange", function (e) {
  12. Y.log("Attribute name = " + e.attrName);
  13. Y.log("Original value = " + e.prevVal + ", New value = " + e.newVal);
  14. Y.log("event trigger" + e.data3); Y.log(e);}, {data3:2}
  15. );
  16.  
  17. //change it
  18. A.set("attrName", "test2");
  19. });
  20. </script>

其他相关

实作范例



回應 (Leave a comment)