在jQuery事件处理程序中调用原型对象方法



我有一个称为 Breadcrumb的对象,该对象具有函数 expandEllipses。以下工作正常:

mbc = jQuery('#breadcrumb').breadcrumb({
    items : initItems
});
jQuery("body").on("click", ".breadcrumb .breadcrumbEllipses",  function(e) {
    mbc.expandEllipses();
});

但是,我想知道如何在我没有对象的jQuery事件处理程序中执行此操作:

jQuery("body").on("click", ".breadcrumb .breadcrumbEllipses",  function(e) {
    parObj = <parent of the .breadcrumbEllipses instance that triggered this event> 
    protoObj = <Prototype object from parentObj>
    protoObj.expandEllipses();
});

这是Barmar的答案最终工作的原因:

jQuery.fn.breadcrumb = function(options) {
    var bc = new Breadcrumb(this, options);
    this.data('breadcrumb', bc);
    return bc;
}; 
jQuery("body").on("click", ".breadcrumb .breadcrumbEllipses",  function(e) {
    bcObj = jQuery(this).closest(".breadcrumb").data("breadcrumb");
    bcObj.expandEllipses();
});

breadcrumb初始化器中,使用.data()

Breadcrumb对象保存在元素中
this.data('breadcrumb', self);

然后您可以稍后检索:

jQuery("body").on("click", ".breadcrumb .breadcrumbEllipses",  function(e) {
    parObj = $(this).closest(".breadcrumb");
    protoObj = parObj.data("breadcrumb");
    protoObj.expandEllipses();
});

最新更新