到达插件外部的方法

时间:2015-06-09 10:01:47

标签: jquery jquery-plugins

我有类似这样的样板,想要达到这个插件内部的一些功能。

 ;
    (function ($, window, document, undefined) {

        'use strict';

        var old = $.fn.twbsPagination;

        // PROTOTYPE AND CONSTRUCTOR

        var TwbsPagination = function (element, options) {
            this.$element = $(element);
            this.options = $.extend({}, $.fn.twbsPagination.defaults, options);

            return this;
        };

        TwbsPagination.prototype = {

            constructor: TwbsPagination,

            destroy: function () {

                return this;
            },

            show: function (page) {

                return this;
            },


            getoptions: function () {
                console.log("run thıs function");
                //return options;
            }

        };

        // PLUGIN DEFINITION

        $.fn.twbsPagination = function (option) {
            var args = Array.prototype.slice.call(arguments, 1);
            var methodReturn;

            var $this = $(this);
            var data = $this.data('twbs-pagination');
            var options = typeof option === 'object' && option;

            if (!data) $this.data('twbs-pagination', (data = new TwbsPagination(this, options)));
            if (typeof option === 'string') methodReturn = data[option].apply(data, args);

            return (methodReturn === undefined) ? $this : methodReturn;
        };

        $.fn.twbsPagination.defaults = {

        };

        $.fn.twbsPagination.Constructor = TwbsPagination;

        $.fn.twbsPagination.noConflict = function () {
            $.fn.twbsPagination = old;
            return this;
        };

    })(jQuery, window, document);

我的问题如何在插件外部获取get选项功能或如何修改插件来执行此操作。 像这样的东西。

var pager = $('#pagination-demo').twbsPagination({
totalPages: 35,
visiblePages: 7

    });
pager.prototype.getoptions());

1 个答案:

答案 0 :(得分:2)

你必须写下这个:

$.fn.getoptions = function() {       
    console.log("run this function");
};

在此之下:

 TwbsPagination.prototype = {
        constructor: TwbsPagination,

        destroy: function () {
            return this;
        },

        show: function (page) {
            return this;
        },
    };

    // HERE goes the function
    $.fn.getoptions = function(option) {       
        console.log("run this function");
    };

问:但是如何从$ .fn.getoptions到达选项并返回选项,当我尝试这个时,它说我未定义

// plugin
 $.fn.getoptions = function(option) {       
        var settings = $.extend({
            // default
            width: "400px"
        }, option );
        console.log("width is: " + settings.width);
    };

你可以像这样访问它:

pager.getoptions({
   width: 100
});

将返回“宽度为:100”