First off, I know this is a base JS issue, not jQuery. I am at that learning point where I cannot seem to get my head completely wrapped around some scope issues. So I need some explanation.
I’ve been reading every article/tutorial I can find, but just need some answers. I setup this base code to experiment with (as the actual code is far too big to post here).
In the following experiment, when the selector1-change button is clicked the ‘cmd’ variable is displayed correctly, but the reference to this.options is ‘undefined’, because it is a different instance of MySelector(), unless I am way off.
So how does one go about calling an instance of an object like this.
Example:
You can use jQueryUI’s dialog by creating it, and then later you can pass commands to it like $(‘#mydiv’).dialog(‘close’); and that will access the instance attached to that element. How is that accomplished?
JQUERY_MYSELECTOR.JS
(function($){
$.fn.MySelector = function(incoming) {
if (typeof(incoming) != 'object') {
return runCommand(incoming);
}
var options = $.extend({},{
id: false,
backgroundColor: false
},incoming);
function runCommand(cmd) {
alert('blah:'+this.options.backgroundColor+"\n"+'cmd:'+cmd);
}
}
})(jQuery);
SCRIPT
<script type="text/javascript" src="jquery_myselector.js"></script>
<script type="text/javascript">
$j(document).ready(function() {
$j('#selector1).MySelector({ backgroundColor: '#000000' });
$j('#selector1-change').click(function() {
$j('#selector1').MySelector('mooocow');
});
});
</script>
STYLE
<input type="button" value="selector1" id="selector1" />
<br/>
<input type="button" value="selector1-change" id="selector1-change" />
UPDATED
Forgot to use the plugin on selector1 (duh)
You’re calling runCommand before you assign a value to options – options has the value
undefinedinside the body of runCommand. Don’t ask me how JS is able to see the body of runCommand before you declare it, but it can.Also, at the first level of MySelector,
thisis bound to the results of running$j('#selector1-change'), which is an array. You will need to iterate that array.Try something like this: