Rod
Rod

Reputation: 15475

How do I create a reusable JavaScript component

I'm trying to create a JavaScript component that is reusable in any web application (pure js only allowed). And more than one instance can exist at a time on a web page.

Client HTML

<head runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" />
    <script src="MyComponent.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            MyComponent.init();
        };
    </script>
</head>

MyComponent.js

var MyComponent = {};

(function () {
    var ns = MyComponent;
    ns.init = function () { alert('test'); }
}());

How would I instantiate the component above?

Upvotes: 0

Views: 150

Answers (2)

Andrei Nemes
Andrei Nemes

Reputation: 3122

Here's the gist of it:

function MyComponent() {
  //constructor
}

MyComponent.prototype.doStuff = function() {
  //method
}

MyComponent.doSomething = function() {
  //static method
}

And heres how you'd use it

var component = new MyComponent();
component.doStuff();

MyComponent.doSomething();

Upvotes: 2

Christophe
Christophe

Reputation: 28154

I think what you are looking for is the constructor pattern. See explanations and the Car example on this page.

Excerpt from the article:

function Car( model, year, miles ) {
  this.model = model;
  this.year = year;
  this.miles = miles;
  this.toString = function () {
    return this.model + " has done " + this.miles + " miles";
  };
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );

Upvotes: 1

Related Questions