Advice needed... Javascript OOP/namespacing

right now i am at a point where i feel that i need to improve my javascript skills because i already see that what i want to realize will get quite complex. I've iterrated over the same fragment of code now 4 times and i am still not sure if it's the best way.

The task:
A user of a webpage can add different forms to a webpage which i call modules. Each form provides different user inputs and needs to be handled differently. Forms/Modules of the same type can be added to the list of forms as the user likes.

My current solution:
To make the code more readable and seperate functions i use namespaced objects. The first object holds general tasks and refers to the individual forms via a map which holds several arrays where each contains the id of a form and the reference to the object which holds all the functions which need to be performed especially for that kind of form.


The structure looks more or less similar to this:

var module_handler = {

    _map  : [],    /* Map {reference_to_obj, id} */

    init: function(){            
        var module = example_module; /* Predefined for this example */
        this.create(module);
    },

    create: function(module) {
        //Store reference to obj id in map
        this._map.push([module,id = this.createID()]);
        module.create(id);
    },

    createID: function(id) {
        //Recursive function to find an available id
    },

    remove: function(id) {

        //Remove from map
        var idx = this._map.indexOf(id);
        if(idx!=-1) this._map.splice(idx, 1);

        //Remove from DOM
        $('#'+id+'').remove();
    }
}

var example_module = {

    create: function(id) {
        //Insert html
        $('#'+id+' > .module_edit_inner').replaceWith("<some html>");
    }
}

Now comes my question ;-)
Is the idea with the map needed?

I mean: Isn't there something more elegant like:

var moduleXYZ = new example_module(id)

which copies the object and refers only to that form.... Something more logical and making speed improvements?? The main issue is that right now i need to traverse the DOM each time if i call for example "example_module.create() or later on any other function. With this structure i cant refer to the form like with something like "this"???


Do you see any improvements at this point??? This would help me very much!!! Really i am just scared to go the wrong way now looking at all the stuff i will put on top of this ;-)

Thank You!


I think you're looking for prototype:

=========

function exampleModule(id)
{
    this.id = id;
}


exampleModule.prototype.create = function()
{

}

=========

var module1 = new exampleModule(123);
module1.create();

var module2 = new exampleModule(456);
module2.create();
链接地址: http://www.djcxy.com/p/17040.html

上一篇: Javascript命名空间/原型问题

下一篇: 需要建议... JavaScript OOP /命名空间