I am trying to create a jQuery plugin. When configuring the plugin, I wish to define an object which will be posted via Ajax. One of the properties in the object value2
is based on the element which the plugin was applied to (a.myClass
), and I thought I would try something like the following:
post:{value1:1,value2:function(t){return $(t).data('id');},value3:3}
But, within the plugin, the object is equal to { value1=1, value3=3, value2=function()}
, and if posted, value2
is sent as undefined
. I've found that I could access the value using settings.post.value2(this)
, however, I don't know how this helps me. I suppose I could loop through the object and evaluate each property, but this just doesn't seem right.
What is the proper way of doing this? Thank you
http://jsbin.com/sedoqeluni/1/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>editSelect</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
(function($){
var methods = {
init : function (settings) {
return this.each(function () {
$(this).click(function(e) {
console.log(settings.post);
console.log(settings.post.value2(this));
$.post('testing.php',settings.post);
});
});
}
};
$.fn.testit = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.testit');
}
};
}(jQuery)
);
$(function(){
$('.myClass').testit({
foo:'bar',
post:{value1:1,value2:function(t){return $(t).data('id');},value3:3}
});
});
</script>
</head>
<body>
<a class="myClass" href="javascript:void(0)" data-id="2">hello</a>
<a class="myClass" href="javascript:void(0)" data-id="222">hello</a>
</body>
</html>