I have got a website where people can share activities just like Twitter, users can Like them and Comment them.
Basically there is a filter that filters the list on date, so for example, show me all activities from today, what will happen is we make a request to our ajax controller, and it will send me the json for each activity based on the filter criteria, I got that all working.
How it works now is, when you press a filter criteria for example “today activities” we call the javascript method LoadActivities(filter); and it will just call the json, parse it and display all activities, now the question is what would be the best way to handle Likes and Comments, how I got it in mind was:
Each like button has the id “ActivityLike_{ACTIVITY_ID}” then make a click event, and split by ‘_’ and voila got the id of the activity, but once the user pressed the like button, it needs to re-render a single activity on the page, because “like” has to change to “not like anymore” etc. Same with commenting.
So how do I build this list, not using splits ‘_’ and other nasty solutions, but how can I do this in a proper clean way? Same question with jQuery “live” events, are they good to use or is there a work around?
Thanks for reading.
Firstly it seems you’re building an application which is heavily reliant on JavaScript, and does very little in terms on progressive enhancement. If this is a well thought out decision, then cool.
One thing I would recommend is to make use of
data-*attributes rather than fiddling around with splitting the ID. Instead ofActivityLike_IDhave a class ofActivityLike, and give each of those elements adata-idattribute of theId. You then have;Awesome.
Because you’ve got simple cases of
like <--> unlikeandcomment <--> remove commentthis should be easy to do in JavaScript. You can add a class to the element when one of the states is selected, or can set a(nother) data attribute. A simple check in your code will let you know what to render the link as.If there’s a chance of more complicated manipulation occurring in future, you may be interested in letting the server control what to change in the page (as it’s likely the server has more context on the request than the client).
Let the server return a data structure like this;
I.e. an array of objects which map to jQuery operations. The
selectordescribes the jQuery selector, theoperatoris the jQuery method to call and theparamsattribute is an array of parameters to pass the method.In the response handler for your AJAX request you can then do;
To handle those operations.
As a concrete example, to give the HTML to unlike an activity, the server could respond with;
Note that
params must be an array (in this example it only has one element).