How to unregister a Magento prototype event handler

How to unregister a Magento prototype event handler

Hello folks, in this article we’ll describe how to unregister an existing Magento prototype event handler and replace it with your custom one. For example, we will replace a Magento default search pop-up using better way.

First of all, you should know the search field id and the event that you want to replace. In our case, the id is “search” and the event is “keydown”. Here is how we can do it:

  //unbind system keydown action
$('search').stopObserving('keydown');

 
After this, you can set your custom handler to the keydown action. Please, look through the following example:

 //new keydown action
var PrettyPopup = Class.create();

PrettyPopup.prototype = {

    getResponse: function(data)
    {
        //Show response
        $('search_autocomplete').innerHTML = data.responseText;
        $('search_autocomplete').show();
        //Restore default icon in search field
        $('search').setStyle({background: 'white'});
    },

    showPopup: function() {
        //hide pop-up
        $('search_autocomplete').hide();
        //search criteria
        var textQuery = $(this.id).value;
        //check if exist value
        if (textQuery == '') {
            return false;
        }

        //reset timer
        clearTimeout(this.searchTimer);

        var nested = this;

        this.searchTimer = setTimeout(function() {
            //show loading icon
            $(nested.id).setStyle({ background:  "white url(" + atwixImagePath + "opc-ajax-loader.gif) no-repeat right" });
            //AJAX request
            new Ajax.Request(
                atwixBasePath + "catalogsearch/ajax/suggest/",
                {method: 'get', parameters: "q=" + textQuery, onComplete: nested.getResponse}
            );

        },750);
        //PROFIT
        return true;

    },

    initialize: function(id) {
        this.id = id;
        //unbind system keydown action
        $(this.id).stopObserving('keydown');
        //init timer variable
        this.searchTimer = 1;
        Event.observe(this.id, 'keyup', this.showPopup.bind(this));
    }
}

Event.observe(document, 'dom:loaded', function(){
    new PrettyPopup('search');
});

We have created a module which is called “Pretty Popup Search” (community edition compatible) with the described feature. You can download it on GitHub and check it out, see the link https://github.com/Atwix/pretty-pop-up-search

At final, we have got something like this:

Thank you for attention, always glad to read your comments :)

Clients

Smart Brands Choose Us.

From Mark Cuban and Sir Richard Branson backed startups, to Inc 500 US Fastest Growing Companies and Global Brands choose us to deliver and support unparalleled eСommerce experience for their customers.