开发者

Javascript function that reassigns itself

How do I keep accordions from being initialized when the page loads... I'd like it only to be run from inside of a method (other than init() of course) but only when needed

$.extend($.fn, {
        accordion: function () {
            var accordion = (function () {
                var accordions = (function () {
                    alert('test');
                    return 1;
                })();

                return {
                    init: function (el) {
                        el.click(func开发者_JAVA技巧tion (e) {
                            accordion.show(el);
                        });
                    },
                    show: function (el) {
                        console.log(accordions);
                    }
                }
            })();

            this.each(function() {
                accordion.init($(this));
            });
        }
    });

I hope I've provided enough detail :-\


$.extend($.fn, {
    accordion: function () {
        var accordion = (function () {
            var accordions = (function () {
                alert('test');
                return 1;
            })();

            return {
                init: function (el) {
                    el.click(function (e) {
                        accordion.show(el);
                    });
                },
                show: function (el) {
                    console.log(accordions);
                }
            }
        })();
    }
});
function theFunctionYouWanted(){
    $('selector').each(function(el) {
        var $el = $(el);
        $el.accordion().init($el);
    });
}

With .extend you're extending jQuery to include a .accordion method. This method returns an object that has an init method so by calling $object.accordion() you get a reference to the accordion object, then you can call it's init method passing it an element.

$el.accordion().init($el)

If you want to see how this is done idiomatically you should take a look at any of the great jquery ui plugins. If you're trying to create a similar style of plugin, the jquery widget factory provides a great starting place for creating reusable UI widgets. See http://blog.nemikor.com/2010/05/15/building-stateful-jquery-plugins/ for more information on the widget factory.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜