tags:

views:

36

answers:

1

Hello,

I'm sort of new to JavaScript programming and I do not understand method access. I have a bit of code that looks like the following:

(function ($) {
    $.fn.myCustomUIElement = function (options) {
        var props = { value: 1  }; 

        return this.each(function () { initialize(); }); 
        function initialize() { /* initialization code */  }

        function toggle() { if (props.value == 1) { props.value = 0; } else { props.value = 1; } }
    };
})(jQuery);

My HTML Page has an anchor tag that is responsible for toggling the state of myCustomUIElement. The HTML that shows this and initializes myCustomUIElement is shown here:

<div id="myElement"></div>        
<a href="#" onclick="toggleFromHtml('myElement');">toggle</a>

<script type="text/javascript">
    $(document).ready(function () {
        $("#myElement").myCustomUIElement();
    });

    function toggleFromHtml(e) {
        $("#" + e).toggle();
    }
</script>

My problem is, the toggle method in the myCustomUIElement object is never called. I can call the toggleFromHtml just fine. How do I access a method that is defined in JavaScript as shown above? Is there a way? Please note, I do not want to re-write the JavaScript shown in the first snippet if possible. If possible, I want to call the method from the toggleFromHtml method.

Thank you!

A: 

I think you have the start of a plugin there, you need to extend the jQuery object. Here is an example, notice $.fn.extend({}) myCustomUIElement() will be your method name

the jQuery plugin

(function($){
$.fn.extend({
    myCustomUIElement: function(options){
        return this.each(function(){
            new $.MyCustomUIElement(this, options);
        });
    }
});

$.MyCustomUIElement = function(target, options){
    var $target = $(target);

    $target.bind('click', {}, function(e){
        e.preventDefault();

        // your event code
        alert(options.myVar + ' ' + $(this).text());
    });
};
})(jQuery);

your init javascript

$(document).ready(function(){
    $('#wrap .myElement').myCustomUIElement({
        myVar: 'click me!'
    });
});

and the HTML

<div id="wrap">
    <a class="myElement" href="#">toggle 1</a>
    <a class="myElement" href="#">toggle 2</a>
</div>
gawpertron