views:

813

answers:

1

What is the problem here? (Besides having redundant code). $.getJSON works as expected. However $.postJSON isn't working. I can inspect $.fn via firebug and sure enough postJSON is listed. However if I try to call it, I get a no function defined error.

jQuery.fn.getJSON = function(path, opts){
  this.extend(opts, {
    url: path,
    dataType: 'json',
    type: 'GET'
  });

  var invalid = opts.error;
  opts.error = function(xhr, status){
    var data = $.httpData(xhr, 'json');
    if (invalid) 
      invalid(data);
  }

  this.ajax(opts);
};

jQuery.fn.postJSON = function(path, data, opts) {
  this.extend(opts, {
    url: path,
    data: data,
    dataType: 'json',
    type: 'POST'
  });

  var invalid = opts.error;
  opts.error = function(xhr, status){
    var data = $.httpData(xhr, 'json');
    if (invalid) 
      invalid(data);
  }

  this.ajax(opts);
};
+3  A: 

jQuery.fn is a reference to the prototype of the jQuery object, which all jQuery constructed objects have access to, so that function becomes jQuery.prototype.postJSON. If you want to declare it as a static method, you should not specify the ".fn"

jQuery.fn.postJSON = function(){};

alert(typeof jQuery.prototype.postJSON ); // function
alert(typeof jQuery.postJSON); // undefined

The reason jQuery.getJSON is a 'function' is because it's a native method of the jQuery object ( it's not the thing you're declaring, which is jQuery.prototype.getJSON );

meder
Yeah just realizing this now, it should certainly be a static method. Thanks.
mikeycgto