📜 ⬆️ ⬇️

Prototype: selectors and events

Prototype is definitely one of the most powerful Javascript libraries, but it has one small drawback which is often mistaken for a big one - the lack of native support for linking selectors to events. For comparison - in <a href=ru jquery.com »jQuery title-> jQuery is one of the main features and it is difficult to imagine <a href = ray jquery.com » in general jQuery without- that title. For those who do not know, this is an opportunity to separate our XHTML from Javascript using CSS selectors, most of such events as onclick , onmouseover , onmouseout , onblur , onfocus and the like.

One of the first solutions to this problem was published by one Ben Nolan . He wrote Behavior a small plugin that solved this problem and is quite suitable now. Its minus is the big footworms of the code for associating selectors with events. Thanks to the jaquery <a href==jquery.com "title- jjuery"> the ease and minimality of writing code on it, some people thought that it was time to imitate the same style in Prototype . And justin Palmer, after a brief hesitation, taking into account the minuses Behavior wrote event: Selectors . This was already much closer to < ja href = you jquery.com »jQuery title-title — jQuery plus the ability to group several or more different selectors with different events. There is no such possibility in <a href = jukery.com "jQuery" title-jQuery ", although in principle it is not in demand. Unfortunately, this plug-in did not develop, and remained in versions 1.0 with some bugs. Most likely, its development has stopped due to the appearance of the next UJS plug-in from the guy with the talking name Dan Webb . His solution is called Low Pro and is a powerful tool as it extends the Prototype Event model. Moreover, I would like to note that this plugin can be used with <a href= pas jquery.com »jQuery title-” “jQuery ”>.
Download Low Pro here

Well, now let's see it in action:

First we include our libraries in XHTML and do not forget - for everything to work your XHTML must be valid , otherwise Javascript may behave unpredictably.
')




In main.js we will add our rules.
Example 1:
  Event.addBehavior ({
	 'div.myclass a: click': function (e) { 
		 alert ('Example 1');
		 return false;
	 }
 }); 

And here is our first rule that intercepts onclick events in all divs with the class myclass for all elements a. return false is needed so that the normal behavior of the element “a” does not work.

Example 2:

  Event.addBehavior ({
	 'div.myclass a: click': function (e) { 
		 alert ('Example 1');
		 return false;
	 },
	 'div [id * = cde]: click, div [id $ = cd]: mouseover, div [id ^ = abcdef]: mouseout': function (e) { 
		 alert ('Example 2');
	 }
 }); 

In this example, CSS uses the third-level attribute selectors and rule grouping.

As you can see everything is very simple, I don’t think to write more examples, better download them here.

Source: https://habr.com/ru/post/23179/


All Articles