Alex
Alex

Reputation: 68440

Best way to define custom jQuery object properties?

I want myproperty to be able to be accessed from other methods within Foo.

Here is the way I'm doing it now:

(function($){
  $.fn.Foo = {

    main: function(){
      return this.each(function(){  

        this.myproperty = 'abc';

        ...
        ...bind('click', 'somemethod')...
        ...

      });
    }

    somemethod: function(e){

      // access here myproperty
      alert($.fn.Foo.myproperty); 
    }

}(jQuery));

(function($){
  $.fn.extend({ Foo : $.fn.Foo.main});
}(jQuery));

and seems to work. But is this the best way to do it? Are there any other ways?

Upvotes: 2

Views: 340

Answers (2)

zero7
zero7

Reputation: 1298

can be exposed via a function of Foo

(function($){
  $.fn.Foo = {

    main: function(){
      return this.each(function(){  

        this.myproperty = 'abc';

        ...
        ...bind('click', 'somemethod')...
        ...

      });

    getmyproperty: function(){
        var myproperty = 'abc'; 
        return myproperty;
    }

    }

    somemethod: function(e){    
      // access here myproperty
      alert($.fn.Foo.getmyproperty()); 
    }

}(jQuery));

Upvotes: 1

Niels
Niels

Reputation: 49919

I think your trying to make a class? You currently are extending the jQuery library with function you can call on elements like $("#test").Foo();

A good start setup is: http://jsfiddle.net/VhGpe/

(function($) {
    var methods = {
        init: function(settings) {
            var options = $.extend({}, $.fn.FooMe.defaults, settings);
            $(this).data("settings", options);
            $(this).bind("click", methods.myOtherFunction);
        },
        myOtherFunction: function() {
            alert($(this).data("settings").you);
        }
    };



    $.fn.FooMe = 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.Foo');
        }
    };

    $.fn.FooMe.defaults = {
        you: "default"
    };

}(jQuery));

$("#test").FooMe({
    you: "TADAA"
});

Upvotes: 2

Related Questions