开发者

Mootools: inject vs adopt

I want to dynamically add some preconfigured HTML-Elements in use of a 'click'-event with mootools.

So I can make it work with my basic knowledge, although it isn´t very nifty. I coded this so far...

This is my preconfigured element, with some text, a classname and some event, cause i wanna have events already added, when it´s inserted into my container:

        var label = ne开发者_如何学编程w Element('label', {
            'text': 'Label',
            'class': 'label',
            'events': {
                'click': function(el){
                    alert('click');
                }
            }
        });

Here is my function, which adds the label-Element:

        function addText(){
            $('fb-buildit').addEvent('click', function(){                   
           row.adopt(label, textinput, deletebtn);
            $('the-form').adopt(row.clone());
            row.empty();

    /*
    label.clone().inject($('the-form'));
    textinput.inject($('the-form'));
    deletebtn.inject($('the-form'));
    */

            });
        }

The second part which uses inject also works, but there, my click-Event, which fires the "alert('click')" works too. The method with adopt doesn´t add any event to my label Object, when its inserted in the dom.

Can anyone help me with this. I just wanna know why adobt ignores my "events" settings and inject doesn´t.

Thanks in advance.

(sorry for my english ^^)


you go label.clone().inject but row.adopt(label) and not row.adopt(label.clone()) -

either way. .clone() does not cloneEvents for you - you need to do that manually.

var myclone = label.clone();
myclone.cloneEvents(label);
row.adopt(label);

this is how it will work

as for why that is, events are stored in the Element storage - which is unique per element. mootools assigns a uid to each element, eg, label = 1, label.clone() -> 2, label.clone() -> 3 etc.

this goes to Storage[1] = { events: ... } and so forth. cloning an element makes for a new element.uid so events don't work unless you implicitly use .cloneEvents()

you are sometimes not doing .clone() which works because it takes the ORIGINAL element along with its storage and events.

suggestion consider looking into event delegation. you could do

formElement.addEvent("click:relay(label.myLabel)", function(e, el) {
    alert("hi from "+ el.uid);
});

this means no matter how many new elements you add, as long as they are of type label and class myLabel and children of formElement, the click will always work as the event bubbles to the parent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜