开发者

Mootools class - storing reference to document body in a class property

Greetings all! I'm trying to learn Mootools classes. I've made this class to add a div to the page.

var F = new Class({

    Implements: [Options, Events],

    options: {
        container: document.body,
        width: '250px',
        background: '#ccc'
    },

    initialize: function(options) {
        this.setOptions(options);
        this.addDemoDiv();
    },

    addDemoDiv: function() {
        var dDiv = new Element('div', {
            'class': 'myClass',
            html: 'Click me!',
            styles: {
                padding: '20px',
                border: '1px solid #999',
                width: this.options.width,
                background: this.options.background
            },
            events: {
                click: this.animate
            }
        });

        dDiv.inject(this.options.container);
    },

    animate: function() {
        alert('Hello world');
    }

});

window.addEvent('domready', function() {

    var item = new F();

});

It's supposed to allow the user to specify the container to inject the div in开发者_StackOverflow社区to, with the document body being the default. When I do it like above, the code validates OK, but the script fails to add the div - Firebug and Chrome complain about the container being null or undefined.

I have to change dDiv.inject(this.options.container); to this

if (!this.container) {
    dDiv.inject(document.body);
} else {
    dDiv.inject(this.container);
}

to make it work.

Can any wise Mootools ninja tell me why inject works when I pass document.body in directly, but breaks when I try to pass it a reference to document.body supposedly stored in the class's container option? I've tried variations on document.body, like 'document.body' and $$('document.body') and $$(document.body).


My guess is that document.body is not available when your class code gets interpreted, this usually occurs when your script is placed in the <head> tags. Moving your script(s) to the bottom of the document (just before </body>) solves a lot and is good practise since your script(s) won't block HTML rendering anymore either.

It's also better to avoid putting a static default DOM references in your class as their availability is always questionable. You can keep options.container null and change your method to:

... code ...
dDiv.inject( this.options.container || document.body );
... code ...

So if this.options.container is not set (falsy) it will default to document.body, this way you can also keep your script(s) in the <head> if you really want to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜