开发者

Getting jQuery to return an ajax object

The question title is a bit strange because I'm not exactly sure how to phrase the problem. The issue is that I have many links to which I want to bind a click event with an ajax call, and I'm just looking to refactor some duplicate code into a single area.

The links I'm trying to bind an ajax call only have one thing that differentiates them, and that's an id from a previously declared object. So I have lots of code that looks like this:

$("a.link").bind('click', function() {
           id = obj.id; 
           $.ajax({ 
                   url: "/set/" + id, 
                   dataType: 'json', 
                   type: "POST" 
           }) 
    });

I was trying to refactor it into something like this:

$("a.link").bind('click', ajax_link(obj.id));

 function ajax_link(id) {
      $.ajax({ 
             url: "/set/" + id, 
             dataType: 'json', 
             type: "POST" 
      }) 
开发者_开发知识库 });

However, as you can imagine, this just actually makes the ajax call when the element is binded with the click event.

Is there an easy way to refactor this code so I can extract out the common ajax code into its own function, and hopefully reduce the number of lines of jQuery in my current script?


This should do what you want:

$("a.link").click(make_ajax);

function make_ajax() {
  $.ajax({ 
    url: "/set/" + id, 
    dataType: 'json', 
    type: "POST" 
  });
}

this in this case refers to the source of the event being the link that was clicked.

It's also possible to define a closure:

$("a.link").click(function() {
  make_ajax(this.id)();
});

function make_ajax(id) {
  return function() {
    $.ajax({ 
      url: "/set/" + this.id, 
      dataType: 'json', 
      type: "POST" 
    });
  };
}

but I don't think that really helps in your example.


You could always put the call to ajax_link in the bound click function,

$("a.link").bind('click', function() {
  ajax_link(obj.id);
});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜