3

So, I've been searching through some existing questions dealing with re-usable items in HTML and Javascript, and I'm not sure if there's anything that gives me the start I'm looking for. I'm not super well-versed in js, but rather than re-write the same code over and over again and have to perform the upkeep on it, I'd prefer to build a re-usable framework that I can apply in several places.

The basic layout is this: There's an input field with an "Add" button, each time you add a name, it displays below the input with a checkbox. When you uncheck it, the name is removed from the list.

I'm fine with styling and building the HTML, what I'm lost on is developing an object in js that I can apply in multiple places. What I had in mind was this:

function createInputControl(targetElementId) {
    var newInputControl = new ItemInputControl();
    newInputControl.onItemAdded = customItemAddedCallback;
    newInputControl.onItemRemoved = customItemRemovedCallback;
    newInputControl.createInElement(targetElementId);
}

That's the start I'm looking for. An object that I can create that has designated callbacks for when an item is added or removed via user interaction, and a way for me to draw it within an existing element on my page.

EDIT: What I'm looking for here is a skeleton of a javascript object (named ItemInputControl above) with these functions / properties that I can re-use throughout my site.

6
  • Strange UI... usually you have unselected checkboxes only, than down below you have buttons saying [remove selected] and [select/unselect All] :) Commented Oct 22, 2014 at 16:47
  • your question provides some basic understanding of OOP in JS. Have you tried anything? At least share some basic HTML and (the best-so-far) JS? (Otherwise looks like please do it for me(free)) Commented Oct 22, 2014 at 17:22
  • I apologize, I'm not looking for someone to just do my work for free. What I'm looking for is a nudge in the right direction of building the ItemInputControl() object, and how the callbacks can be designated within it. I'm fine writing out the necessary HTML. I built the control once already with HTML and JS, but it was specific to that location on the site. I'd like functionality so that I can say "okay, take this basic concept, and apply it on another page, and another page" Commented Oct 22, 2014 at 17:51
  • not exactly OOP but: jsfiddle.net/oq67yton/1 Commented Oct 22, 2014 at 17:55
  • The Dojo/Dijit libraries tend to use this principle pretty well; ie, you can declare new Button({onClick: this.processSubmit}, buttonElement); to make a Button widget that replaces buttonelement's content. It all translates to HTML in the end. Commented Oct 22, 2014 at 18:35

2 Answers 2

1

Ok, so If I understand you correctly - you're looking for help on how to make a globally accessible variable that can be used in your entire application, like jQuery. You have two main options for what you are looking to do

First - you could use an Object Literal, which exposes a single global variable and all of your methods are contained within:

(function (window) {
    var inputControl = {
        onItemAdded: function () {
            // do stuff
        },
        onItemRemoved: function () {
            // do stuff
        },
        createInElement: function (targetElementId) {
            // do stuff
        }
    };
    window.ItemInputControl = inputControl;
})(window);

This is used like so:

ItemInputControl.createInElement("elementId");

Your second option is to use Prototype:

(function (window) {
    var inputControl = function () {
        // Constructor logic
        return this;
    };
    inputControl.prototype.onItemAdded = function () {
        // do stuff
        return this;
    };
    inputControl.prototype.onItemRemoved = function () {
        // do stuff
        return this;
    };
    inputControl.prototype.createInElement = function (elementId) {
        // do stuff
        return this;
    };
    window.ItemInputControl = inputControl;
})(window);

This would be used like so:

var newInputControl = new ItemInputControl();
newInputControl.createInElement("elementId");

For most cases in individual applications - I prefer to use Object Literals for my framework. If I were building a widely distributed javascript framework, I would probably use a prototype pattern. You can read more on prototype patters here: http://www.htmlgoodies.com/beyond/javascript/some-javascript-object-prototyping-patterns.html

Sign up to request clarification or add additional context in comments.

4 Comments

Okay, this is extremely helpful. The link is great too. Again, being new with this, I'm not entirely sure which approach I would take, but I'm glad that you were able to decipher my question. I'm working on this now and will let you know where I get with it. Thanks.
Thanks, let me know if you have any other questions. Please upvote and accept if my answer helped you. Thanks!
Can't upvote yet, too new! If this all works out well for me I'll just accept it. It's a start, and all I was looking for was a start. Thanks.
Okay, so this answer was definitely helpful, and the link you provided even more so. I was able to build the ItemInputControl() that I was hoping to, and I could designate the proper callbacks for when an item is added or removed. I should say I had a ton of difficulty when creating the new items after someone clicks "Add Item" and adding event handlers to those new items so that they would hit the proper callbacks on "Remove". That is, until I came across this question: stackoverflow.com/questions/6985288/… which helped a TON
0

Well, I'm not sure if this is exactly helpful, but perhaps it will contain a few ideas for you.

The two HTML elements needed are stored as format strings, and everything is dynamically added/removed in the DOM.

var listid = 0;

    $(document).ready(function() {

        var controlHtml = + // {0} = mainid
            '<div>' +
                '<input id="text-{0}" type="text" />' +
                '<div id="add-{0}" class="addButton">Add</div>' +
            '</div>' +
            '<div id="list-{0}"></div>';

        var listHtml = +  // {0} = mainid, {1} = listid, {2} = suplied name
            '<div id="list-{0}-{1}"><input id="checkbox-{0}-{1}" type="checkbox class="checkboxClass" checked />{2}<div>';

        $('#content').append(controlHtml.f('0'));

        $('.addButton').click(function(e) { addClick(e); });

    });

    function addClick(e) {
        var id = e.currentTarget.id.split('-')[1];
        var name = $('text-' + id).val();
        $('.list-' + id).append(listHtml.f(id, listid, name));
        listid++;
        $('.checkboxClass').click(function() { checkboxClick(e); });
    }

    function checkboxClick(e) {
        $('#' + e.currentTarget.id).remove();
    }

    String.prototype.f = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); };

And of course very minimal HTML to allow a hook for adding your control:

<body>
    <div id="content"></div>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.