jquery plugin: multiple call to a function, passing different parameters – Education Career Blog

I’ve got a tricky problem.

I’ve made a jquery Widget plugin :

$.fn.Widget=function(id_place,id_event,options){};

I call it once when the page is ready : (specifying that I want a last sorting)

$(document).ready(function() {
    $('#mydiv').Widget(13,50,{"sort":"last"});

});

But in this plugin, I generate a little menu bar, with 3 links to change the sorting of my elements : “last” (initial call); “top” (most popular) and “answered” (with answers)

My question is : how to, in this generated code inside my plugin, Sort PopularSort LastSort answered, change the sorting of my Widget??

Can I call Widget(13,50,{"sort":"top"}) inside of it, Or can I use a inside function like change_sorting(top)??

Thx a lot for your time and your help

EDIT: Thanks for your answers: I’ve added these lines in my plugin:

var object = $(this);
    $(".sort_last").click(function(){ object.Widget(13,50,{"sort":"last"}); });
    $(".sort_top").click(function(){ object.Widget(13,50,{"sort":"top"}); });
    $(".sort_answered").click(function(){ object.Widget(13,50,{"sort":ansered"}); });

,

1st of all it is good idea to check for elements existence before creating them.
2nd – considering how other jquery methods work, best would be to use Widget(13,50,{"sort":"top"}) for both creation and updating

,

If the change in sorting is made by the user, it shouldn’t be in the Widget constructor. You can easily change the value of Sort in the constructor with options.sort = "newSort";, but I think you want something different.

Consider adding a method to the object such as:

$.fn.Widget.prototype.changeSort(sort) {
  // add your sorting code here, using this.sort as the current sort
}

which will handle all the changing of the Sort; this way it helps abstracting the sorting mechanism from actually creating the Widget (they seem like different things to me).

If you wanted access to the current Sort in your method, you can assign it to “this” in the constructor:

this.sort = options.sort and then reference it with this.sort in any methods on the Widget prototype.

So you can then do:

$(function() {
  var widget = $('#mydiv').Widget(13,50,{ sort: 'last' });
  widget.changeSort("answered");
});

Leave a Comment