yui3 的泡你冒了吗?

先不废话,直接代码。 [html] <button value="Fire" id="fire">Fire publisher:testEvent</button><br/> <input type="checkbox" id="stopPropagation"> <label for="stopPropagation">Stop Propagation (testEvent won't bubble to the BubbleTarget.)</label><br/> <input type="checkbox" id="preventDefault"> <label for="preventDefault">Prevent Default (testEvent's defaultFn won't fire.)</label> <ol id="log"> <li>Custom Event log messages will appear here.</li> </ol> <script src="http://yui.yahooapis.com/3.1.1/build/yui/yui-min.js"></script> [/html] [javascript] YUI().use('node','event-custom-complex',function(Y){ var BubbleTarget = function() { Y.log("Host constructor executed.", "info", "example"); } var Publisher = function(bubbleTarget) { this.addTarget(bubbleTarget); this.publish("publisher:testEvent", { emitFacade: true, defaultFn: function() { Y.log("defaultFn: publisher:testEvent's defaultFn executed.", "info", "example"); }, preventedFn: function() { Y.log("preventedFn: A subscriber to publisher:testEvent called preventDefault().", "info", "example"); }, stoppedFn: function() { Y.log("stoppedFn: A subscriber to publisher:testEvent called stopPropagation().", "info", "example"); } } ); /**/ } Y.augment(BubbleTarget, Y.EventTarget); Y.augment(Publisher, Y.EventTarget); //p will bubble to bubbleTarget var bubbleTarget = new BubbleTarget(); var p = new Publisher(bubbleTarget); //bubbleTarget.on is method two bubbleTarget.subscribe("publisher:testEvent", function(e) { Y.log("publisher:testEvent fired on the BubbleTarget object.", "info", "example"); }); //p.on is method two p.subscribe("publisher:testEvent", function(e) { Y.log("publisher:testEvent subscriber fired on the publisher object.", "info", "example"); if(Y.one("#stopPropagation").get("checked")) { e.stopPropagation(); } if(Y.one("#preventDefault").get("checked")) { e.preventDefault(); } }); var logger = Y.one("#log"); Y.on("click", function(e) { logger.set("innerHTML", ""); p.fire("publisher:testEvent"); }, "#fire"); Y.on("yui:log", function(e) { var s = logger.get("innerHTML"); logger.set("innerHTML", s + "<li>" + e.msg + "</li>"); }); }); [/javascript] yui3 无疑是当今javascript框架的巨星,尤其是受大团队的青睐,说实话,yui3之前的yui1,yui2,我一直没有重视过这个框架,尽管脚本大神Douglas Crockford一再强调它有多好。但yui3不得不让我辈另眼相看,从它的设计模式到加载机制,从它的核心到它的粒度,不能像taobao高手李晶说的那样不尽完美,但它绝对值得我们花点时间来探索一下。如果说jquery是一个可装卸的可定制的千手观音,那yui3就是一个变形金刚。这个自定义事件就是这个变形金刚的一个很牛X的变化花样。 这里我大致说一下它的原理,不明白的可以留言。 原理:执行一个(对象1)的一个函数(方法,事件)的同时,联动的去执行与它捆绑在一起的(对象2)的同名函数(方法,事件)。以此类推。 这就是yui3自定义事件的冒泡原理,说白了就是一个对象的函数执行,另外一个对象的同名函数也跟着执行。不要小看这个花样,在模块式开发中,它很好玩儿!没玩儿的,快去玩玩儿。不会的我教你玩儿。对了还有一张图片,很形象。
posted @ 2010-08-17 09:33  7hihi  阅读(227)  评论(0编辑  收藏  举报