Proper technique to add listeners to DOM created via an XTemplate?

前端 未结 4 1085
刺人心
刺人心 2020-12-24 15:31

We use XTemplates - lots of XTemplates. They are great for displaying read-only content. But have you ever added (Ext JS) listeners to DOM created via a template? Would y

4条回答
  •  生来不讨喜
    2020-12-24 15:44

    My preferred technique is using the analog of $.live function from jquery. F.i. let's assume you are going to use xtemplate for creating simple list like the following:

    
    

    To assign handler to the anchors you would do in jquery something like:

    $('.nav a').live('click', function(){
        // do something on anchor click
    });
    

    The $.live function is great because it would work even if handler assignation would happen before list rendering. This fact is extremely important when you use xtemplate.

    Fortunately there is analog in ExtJs - delegating events. Just look at the code:

    Ext.getBody().on('click', function(event, target){
            // do something on anchor click
        }, null, {
            delegate: '.nav a'
        });
    

    For more info take a look at docs for the Ext.Element.addListener method.

提交回复
热议问题