0

我最近遇到了一种情况,我想在基本级别更改Bootstrap的默认行为。我想自定义方法添加到Modal类,以自定义的方法可以被称为像任何其他股票Modal方法:将自定义函数添加到Bootstrap.js

$('#my-modal').modal('myMethod', myParameter); 

我必须通过向Modal的构造函数这个工作:

$.fn.modal.Constructor.prototype.myMethod = function (myParameter) { 
    ... 
} 

然而,myParameter变量没有被传递。如何访问/将myParameter传递给自定义Bootstrap方法?

回答

0

我找到了一种方法来做到这一点,但不幸的是它涉及Bootstrap源代码的更改。的代码段完成实际方法调用是这样的:

$.fn.modal = function (option) { 
    return this.each(function() { 
    var $this = $(this) 
     , data = $this.data('modal') 
     , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) 
    if (!data) $this.data('modal', (data = new Modal(this, options))) 
    if (typeof option == 'string') data[option]() 
    else if (options.show) data.show() 
    }) 
} 

为了改变这种情况,第7行(在source code线206)应该被修饰以通过最初传递给封闭函数的任何其他参数。另外,必须将原始参数赋予jQuery的.each()函数的每个迭代。这里的工作代码:

$.fn.modal = function (option) { 
    return this.each(function() { 
    var $this = $(this) 
     , data = $this.data('modal') 
     , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) 
    if (!data) $this.data('modal', (data = new Modal(this, options))) 
    if (typeof option == 'string') data[option].apply($this.data('modal'), Array.prototype.slice.call(arguments, 1)); // pass the parameters on 
    else if (options.show) data.show() 
    }, arguments) // execute each iteration with the original parameters 
} 

我仍然在尝试,以确保这种变化不会产生任何不良的副作用,但到目前为止,一切正常。任何更优雅的解决方案将受到欢迎。

0

你没有办法这样做。 The code模型用于调用函数不考虑参数;

$.fn.modal = function (option) { 
    return this.each(function() { 
     var $this = $(this) 
     , data = $this.data('modal') 
     , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) 
     if (!data) $this.data('modal', (data = new Modal(this, options))) 
     if (typeof option == 'string') data[option]() // <-- here 
     else if (options.show) data.show() 
    }) 
    } 

你最好的选择将是一个方法添加到$.fn,然后通过$(this).data('modal')检索Model实例,因为这是在那里引导存储实例;

$.fn.foo = function (param) { 
    return this.each(function() { 
     var model = $(this).data('modal'); 

     // blah blah blah 
    }); 
}