非常简单的事件驱动的jQuery插件设计模式

时间:2018-03-22 14:04:17

标签: javascript jquery design-patterns jquery-plugins jquery-events

有时我有多个元素需要FORMATS.values.max { |values| values.length }.size回调函数和一些常用功能,并且实现如下:

click

我没有使用某个功能,而是尝试创建一个非常简单的插件。  我已经成功地创建了https://learn.jquery.com/plugins/advanced-plugin-concepts/所描述的灵活jQuery插件,但是,我认为对这些类型的应用程序这样做是过度的,并且希望使用drop-dead插件设计模式。我的最新尝试是在下面,但是,我没有成功传递function deleteRecord(elem, url, type) { if (confirm("Are you sure you wish to delete this "+type+"?")) { $.ajax({ type:'DELETE', url: url, dataType: 'json', success: function (rsp){ $(elem).closest('tr').remove(); }, error: function (xhr) { alert('Error: '+xhr.responseJSON.message); } }); } } $("#manual-list img.delete").click(function() { deleteRecord(this, '/1.0/manuals/'+$(this).closest('tr').data('id'),'manual')}); 参数,该参数是由应用插件的元素派生的。

有哪些选项可用于非常简单和简洁的jQuery事件驱动插件?

url

1 个答案:

答案 0 :(得分:2)

您忘记了返回声明:

function(){'/1.0/manuals/'+$(this).closest('tr').data('id')}

将其更改为:

function(){return '/1.0/manuals/'+$(this).closest('tr').data('id');}



(function ($) {
    $.fn.deleteRecord = function (url, type) {
        console.log('init', url, type, url.call(this, url, type));
        console.log('----')
        this.click(function () {
            //Confirm that this.each(function(){...}) is not required
            console.log('onClick', url, type, this, url.call(this, url, type))
            if (confirm("Are you sure you wish to delete this " + type + "?")) {
                console.log('onConfirm', url, type, this, url.call(this, url, type))
                var e = this;
                $.ajax({
                    type: 'DELETE',
                    url: url.call(this, url, type),
                    dataType: 'json',
                    success: function (rsp) {
                        $(e).closest('tr').remove();
                    },
                    error: function (xhr) {
                        alert('Error: ' + xhr.responseJSON.message);
                    }
                });
            }
        })
        return this;
    };
})(jQuery);


            $("#manual-list img.delete").deleteRecord(function(){return '/1.0/manuals/'+$(this).closest('tr').data('id');},'manual');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table id="manual-list">
    <tr data-id="1">
        <td>
            <img class="delete" src="https://dummyimage.com/200x200/000/fff&text=1">
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

相关问题