How can I use object o outside the jQuery plugin scope? I have the following snippet:
var o ={};
(function ($) {
$.fn.extend({
gridView: function (options) {
var defaults = {
grid :{
renderTo : '#container',
},
gridHeader: {
************
***********
};
var options = $.extend(defaults, options);
return this.each(function () {
o = options; // i was expecting this step to fill the object
var obj = $(this);
if( o.search.enabled){$(o.grid.renderTo).
append('<div class="headerSearch">
<input name="tbSearch" type="text" onchange="" onkeypress="do_this();"
id="tbSearch"><img src="'+ o.search.imgUrl +'" alt="Search"></div>')
})(jQuery);
console.log(o) ; // this gives me an empty object
My other Question is, how and where you can create a function the can be called onkeypress
so this do_this(); function can also see the object?
This doesn’t make any sense, and can’t work. Your jQuery code is invoked (presumably) at some later time via a
$("selector").gridView()and that is when your plugin executes. Until then, nothing inside yourgridView: functionhas run, and the value ofohasn’t been modified when your code reachesconsole.log(o).If you want to persist some data tied to an element, you should use
$.datato get and set data attributes on the element your plugin is being bound to. The section on Data in the jQuery Plugin Authoring page will be very useful.