自定义JQuery插件方法错误
Custom JQuery Plugin Method error
我一直在为我的一个web应用程序编写自定义jquery插件,但我一直遇到一个奇怪的错误,我认为这是由于我不熟悉面向对象的编程。
当我尝试运行$(".list-group")时,我遇到了错误。updateList('template', 'some template')两次,第一次它工作得很好,但第二次我运行相同的命令,我得到一个对象不是函数错误。下面是插件代码:
(function($){
defaultOptions = {
defaultId: 'selective_update_',
listSelector: 'li'
};
function UpdateList(item, options) {
this.options = $.extend(defaultOptions, options);
this.item = $(item);
this.init();
console.log(this.options);
}
UpdateList.prototype = {
init: function() {
console.log('initiation');
},
template: function(template) {
// this line is where the errors come
this.template = template;
},
update: function(newArray) {
//update code is here
// I can run this multiple times in a row without it breaking
}
}
// jQuery plugin interface
$.fn.updateList = function(opt) {
// slice arguments to leave only arguments after function name
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var item = $(this), instance = item.data('UpdateList');
if(!instance) {
// create plugin instance and save it in data
item.data('UpdateList', new UpdateList(this, opt));
} else {
// if instance already created call method
if(typeof opt === 'string') {
instance[opt](args);
}
}
});
}
}(jQuery));
我注意到一件事,当我去访问这个。template -它在一个数组中,所以我必须调用这个。模板[0]获取字符串…我不知道它为什么这样做,但我怀疑它与我得到的错误有关。也许第一次可以赋值字符串,但第二次不行?任何帮助将不胜感激!
谢谢
this.template = template
实际上是您的问题,因为您正在覆盖在实例上设置的函数。当你把它作为参数传递给初始的template
函数时,你最终会把它覆盖到你的args
数组。它基本上会这样做:
this.template = ["some template"];
因此,instance[opt](args)
下次运行时,它将尝试执行该数组,就好像它是一个函数,因此得到非函数错误。
JSFiddle
相关文章:
- 未捕获错误:无法在初始化之前调用方法;
- 为什么我得到错误IE修剪方法是't支持
- 错误405:向Java控制器(Ajax)发送JSON时找不到POST方法
- 处理浮点错误的最佳方法是什么
- AngularJS错误:提供程序必须从$get工厂方法返回值
- SignalR:调用集线器方法时出现内部服务器错误
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 使用javascript ajax post方法的未定义偏移PHP错误
- Push方法显示错误
- 修复AngularJS错误:提供程序必须从$get工厂方法返回值
- $resource上带有.then()函数的角度自定义方法导致错误
- 克服错误的更优雅的方法是什么:需要对象说明符.当通过JXA通过Messages发送SMS时,参数没有对象说明符
- jQuery AJAX Post方法错误(语法错误)
- 在Javascript中调用对象方法时不是函数类型错误
- 操作映射触发控制器中的错误方法
- Backbone JS Model Fetch在Fiddler中返回200,但调用错误方法
- 未捕获的类型错误:方法不是函数
- 如何在重写Backbone'时触发错误?方法
- Google Web 工具包运行时错误:方法中缺少非本机或抽象方法中的“代码”属性
- 在NPObject上调用错误方法