The jQuery documentation suggests storing additional info per DOMElement using data(). But I'm having a hard time accessing the saved data in a good way.
The scope changes when I call other functions which makes me lose my way :)
(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('myPlugin');
if (!data) {
$(this).data('myPlugin', {
testValue: true
});
data = $this.data('myPlugin');
}
});
},
testFunction: function () {
console.log('t: '+$(this).data('myPlugin').testValue);
methods.otherFunction();
},
otherFunction: function () {
console.log('o: '+$(this).data('myPlugin').testValue);
}
};
$.fn.myPlugin = 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.myPlugin');
}
};
})(jQuery);
$(document).ready(function () {
$('body').myPlugin();
$('body').myPlugin('testFunction');
});
Console output:
t: true
Uncaught TypeError: Cannot read property 'testValue' of undefined
You need to use
methods.otherFunction.apply(this);
instead of
methods.otherFunction();
to make the scopes correct.
Demo: http://jsfiddle.net/ayNUD/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With