I have a really noob question about ajax widgets. It's really an extension of a question I asked a while ago: ajax widgets in pyramid and chameleon
If you look at this question and the contents of the file account_login_widget.pt, you'll see the 'widget' uses syntax like ${username}. This works again for a login widget of which there is only ever one on a page, but all hell breaks loose trying to use this 'widget pattern' for widgets that can exist multiple times on a page.
Now I want to create an ajax toggle button. The button should be configurable: the text of the button can change depending on the page it's used on, and the callback code should be able to be changed too...again depending on the page. Additionally multiple toggle buttons should be able to exist on the same page.
2 questions:
Let's say I have a list of restaurants on my page and a 'Like' button next to each. What is the correct way to pass the restaurant id to the 'post' server call (ie: how do you pass variables to the javascript widget?).
On the same page, let's say I want to use the same ajax toggle button widget, but in a different context. Let's say, on the same page I also have a list of people and I want to 'Follow' them. What's the correct way to pass the button text variable into the widget and also change the post server call behavior? (ie: In question 1 maybe I want to call restaurant.like(), but in question 2 I want to call person.follow()
Here is some sample code showing the widget...
<script type="text/javascript">
// plugin implementation
(function($) {
$.fn.create_ajax_toggle_button = function(csrf, name, toggle_on, url, on_text, off_text) {
return this.each(function() {
var anchor = $('<a></a>');
anchor.appendTo(this);
$(anchor).button();
$(anchor).toggle_ajax_button_text(toggle_on, on_text, off_text);
$(anchor).click(function(e) {
var form_data = '_csrf=' + csrf + '&name=' + name + '&toggle_on=' + toggle_on;
$.post(url, form_data, function(response) {
$.fn.toggle_ajax_button_text();
});
});
});
};
$.fn.toggle_ajax_button_text = function(toggle_on, on_text, off_text) {
if (toggle_on == 'True') {
$(this).toggleClass('ui-state-active');
$(this).text(on_text);
} else {
$(this).text(off_text);
}
};
})(jQuery);
// Define the entry point
$(document).ready(function() {
// YUCK!!! I really shouldn't be/can't using ${name} templating
// syntax like this. Doing this means the JS code needs to be
// loaded over and over again for each item in the list. This
// just doesn't work. :-(
$('.ajax_toggle_button_div_${name}').create_ajax_toggle_button('${csrf}', '${name}', '${toggle_on}', '${url}', '${on_text}', '${off_text}');
});
</script>
<div class="ajax_toggle_button_div_${name}"></div>
Thanks!