Yes, I understand that JavaScript doesn’t have “classes” per se, so I’ll just throw that out there up front and move on.
I have an app that has a left sidebar that lists a bunch of tags. I’m manipulating these tags via JavaScript and AJAX to add, remove, and update the tags.
When I currently manipulate the tags, it goes something to the effect of (note this code is a dumbed-down version of what I’m doing, but conveys the point; also, I’m using the jQuery library):
# HTML page...
<div id="tags">
<div class="tag" id="tag_1">tag text</div>
<div class="tag" id="tag_2">tag text</div>
<div class="tag" id="tag_3">tag text</div>
...
</div>
# Javascript to create new tag
$("#tags").append("<div class='tag' id='tag_15'>text</div>")
# update a tag
$("#tag_10").replace("<div class='tag' id='tag_10'>updated tag</div>")
# remove a tag
$("#tag_10").remove()
As a side note, I’m using the Rails framework and some of the JS is created on the server via js.erb files and sent back to the client to evaluate. I’m aware of some concerns with servers generating JS, but it’s OK in this situation.
So I decided that I should group this functionality into a JavaScript “class” that controls the tags on my page.
The issue is that I have a single tags sidebar, so I don’t need multiple Tag objects…I just need a bunch of named methods that allow me to manipulate the tags on my page in an orderly fashion.
I would like to be able to do things like:
Tag.append({ text: "tag text", id: <id of tag> }) => the append functionality above
Tag.update(<id to update>, { <hash of options> })
Tag.remove(<id of tag to remove>)
I don’t understand how I would achieve this functionality with JavaScript.
My thoughts are doing something like:
# "class" definition
function Tag() {
var methods = {
init : function() { ... }
append : function(options) {
var element = <...build DIV element...>;
$("#tags").append(element);
}
remove : function(domid) {
$(domid).remove();
}
}
}
# usage
var tag = Tag.new()
tag.remove("tag_10")
...
However, if I do it this way, will I have to create a new var tag = Tag.new() each time I want to reference the Tag class (since I’m sending some code back via the server)?
Another option is to group your functions as a jQuery plugin, returning an object with chainable utility functions: