Javascript 在样板插件中创建添加/删除或刷新函数

Javascript 在样板插件中创建添加/删除或刷新函数,javascript,jquery,Javascript,Jquery,我正在构建一个简单的插件,它只构建一个表: ; (function ($, window, document, undefined) { // Create the defaults once var pluginName = "tableBuilder", defaults = { }; // The actual plugin constructor function Plugin(element, options) {

我正在构建一个简单的插件,它只构建一个表:

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

    // Create the defaults once
    var pluginName = "tableBuilder",
        defaults = {
        };

    // The actual plugin constructor
    function Plugin(element, options) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    String.prototype.format = function (values) {

        var regex = /\{([\w-.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g;

        var getValue = function (key) {
            var value = values,
                arr, type;

            if (values == null || typeof values === 'undefined') return null;

            if (key.indexOf('.')) {
                arr = key.split('.');

                while (arr.length && value) {
                    value = value[arr.shift()];
                }
            } else {
                value = val && val[key] || values[key];
            }

            type = typeof value;

            return type === 'string' || type === 'number' ? value : null;
        };

        return this.replace(regex, function (match) {
            //match will look like {sample-match}
            //key will be 'sample-match';
            var key = match.substr(1, match.length - 2);

            var value = getValue(key);

            return value != null ? value : match;
        });
    };

    Plugin.prototype = {

        init: function () {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.options).

            this.cycle();
        },

        cycle: function() {
            var self = this;

            self.buildRow();
            self.display();
        },

        buildRow: function () {
            var self = this;
            self.rows = [];

            $.each(self.options.json, function (i, item) {
                self.rows.push(self.options.rowTemplate.format(item));
            });

            console.log(self.rows);
        },

        display: function (el, options) {
            var self = this;

            $(self.element).html(self.rows.join());
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName,
                new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);
我通过一个按钮点击事件将其称为:

var row = "<tr data-id=\"{Id}\"><td>{FileName}</td><td>{Metadata.FileSize}</td><td></td><td><button type=\"button\" class=\"close\" data-id=\"{Id}\" aria-hidden=\"true\">&times;</button></td></tr>"

$("#assets").on("click", ".glyphicon", function () {
    var $asset = $(this).parent();
    var $actionBar = $("#action-bar");
    var $selected = $("#selected-asset");
    var $table = $(".table");

    var currentSelected = parseInt($selected.text());
    var assetId = parseInt($asset.attr("id"))

    if ($asset.hasClass("active")) {
        $selected.text(currentSelected - 1);
        activeItems = $.grep(activeItems, function (obj) {
            return obj.Id != assetId
        });
        $asset.removeClass("active");

        if (activeItems.length <= 0) {
            $actionBar.hide();
        }
    } else {
        $selected.text(currentSelected + 1);
        var asset = $.grep(assets, function (obj) {
            return obj.Id == assetId
        });

        activeItems.push(asset[0]);
        $asset.addClass("active");

        $actionBar.show();
    }

    $("#assets-table").tableBuilder({
        json: activeItems,
        rowTemplate: row
    });
});
var row=“{FileName}{Metadata.FileSize}×;”
$(“#资产”)。在(“单击“,”.glyphicon“,函数(){
var$asset=$(this.parent();
var$actionBar=$(“#actionBar”);
var$选定=$(“#选定资产”);
var$table=$(“.table”);
var currentSelected=parseInt($selected.text());
var assetId=parseInt($asset.attr(“id”))
if($asset.hasClass(“活动”)){
$selected.text(currentSelected-1);
activeItems=$.grep(activeItems,函数(obj){
返回对象Id!=assetId
});
$asset.removeClass(“活动”);

如果(activeItems.length我将自己回答这个问题:) 基本上,我认为这不是处理我的小部件的最佳方式,因此我使用了来解决我的问题。我将我的单击事件修改为:

$("#assets").on("click", ".glyphicon", function () {
    var $asset = $(this).parent(); // Get our asset element
    var $actionBar = $("#action-bar"); // Get the action bar
    var $selected = $("#selected-asset");// Get our selected asset counter

    var currentSelected = parseInt($selected.text()); // Get our current counter value
    var assetId = parseInt($asset.attr("id")); // Get the asset id
    var asset = $.grep(assets, function (obj) { // Find our asset from our array
        return obj.Id == assetId;
    });

    if ($asset.hasClass("active")) { // If our asset is already selected, then we must unselect it
        $selected.text(currentSelected - 1); // First, decrease our counter
        tableWidget.tableBuilder("remove", asset[0]); // Then call our widget and remove the current asset from the table
        activeItems = $.grep(activeItems, function (obj) { // Repopulate our array of active assets
            return obj != asset;
        });
        $asset.removeClass("active"); // And remove the active class from our element

        if (activeItems.length <= 0) { // Finally, if this is the only selected asset
            $actionBar.hide(); // Hide our actionbar
        }
    } else { // Else, we are selecting an asset
        $selected.text(currentSelected + 1); // Increase our counter
        tableWidget.tableBuilder("add", asset[0]); // Add a row to our widget
        activeItems.push(asset[0]); // Add the asset to our array of active assets
        $asset.addClass("active"); // Add our active alss to our element

        $actionBar.show(); // And show our actionbar
    }
});
这就是我现在解决问题的方法。您可以看到我通过调用

tableWidget.tableBuilder("add", asset[0]);
并通过调用以下命令删除项目:

tableWidget.tableBuilder("remove", asset[0]);
我真的希望这能帮助别人:D

干杯,
好的,所以我对我的最后一个答案没什么印象。 借助此视频:

我能够计算出所有函数实际上都是插件实例的一部分。 下面是我的新插件:)

现在,我需要访问的函数是add()remove(),因此如果您查看以下几行:

$.fn[pluginName] = function (options) {
    return this.each(function () {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName,
            new Plugin(this, options));
        }
    });
};
它们实际上是将实例传递到$.data数组,该数组允许我使用一行代码调用实例:

$("#assets-table").data("plugin_tableBuilder")
因此,我可以调用该实例中的任何函数,如下所示:

var row = "<tr data-id=\"{Id}\"><td>{FileName}</td><td>{Metadata.FileSize}</td><td></td><td><button type=\"button\" class=\"close\" data-id=\"{Id}\" aria-hidden=\"true\">&times;</button></td></tr>"
var tableWidget;

$(function () {
    tableWidget = $("#assets-table").tableBuilder({
        rowTemplate: row
    });
});
$("#assets-table").data("plugin_tableBuilder").add(asset[0]); // Add a row to our widget
我希望这能帮助其他人:D


/r3plica

唯一的问题是它需要jquery ui
$("#assets-table").data("plugin_tableBuilder")
$("#assets-table").data("plugin_tableBuilder").add(asset[0]); // Add a row to our widget