开发者

Why aren't options being overridden?

In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[in开发者_如何学Godex] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();


... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/


var options = { /* ... */};
Framework.MyModule = (function(options) {
  /* .. options are undefined ... */
})();

Framework.MyModule = (function(options) {
  /* .. options are defined... */
})(options);

Now if you want the ability to add private/public variables AND still pass options you will need to make it so the a constructor method is returned with your public object - thus not passing options in the function that is run immediately. Because lets be honest .. this doesn't really make sense.


You could do something like this:

var Module = {};
Module.Foo = (function($){ // jQuery is accessible as $
    var _private = {
        defaults: {
            url: '/default-url', container: '#dummy'
        },
        foos: []
    };

    return function(o){ // returns constructor
        // other _private variables are accessible here
        var opts = $.extend({}, _private.defaults, o);
        var self = { // public return object
            load: function(){
                $(opts.container).load(opts.url);
            }
        };
        _private.foos.push(self);
        return self;
    };
})(jQuery); // scope global variables


var foo1 = Module.Foo({
    url: '/test.php', 
    container: '#success'
});

var foo2 = Module.Foo({
    url: '/test2.php', 
    container: '#success2'
});

foo1.load();
foo2.load();


You're not passing in any options to the anonymous function call.

your call would have to end with })(options); if you want it to use custom options.


You're executing the function immediately. That function returns module, which is an object, not a function. Did you mean instead to return a function?

Then call it using:

Framework.MyModule(options);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜