开发者

namespacing with js prototype framework

When you create a class in the name space of example.

em.components.grid

em.components.grid.Popup = Class.create(
{
  initialize: function(params){
    ...
  },

  show:function(){
    // create or show 
  }
});

Does this mean in other classes I have access to the show method if I use the namespace path above.

// Another class in prototype
em.components.grid.Popup.show();

Or does your new class your trying to access show from have to be in the same namespace.

Is namespacing kind of like packages in other languages. So by giving a namespace you can keep all your classes related to for example grid in one name space and possible other classes unrelated to grid in another namespace.

Update This raises 2 other questions, lets say i create my class like above with the same namespace. Then in another js document I instantiate the class

var popup = new em.components.grid.Popup()

Then popup would be a global variable not? which I don't want to have in my files if possible. Seen as I have went to all the trouble of giving it a unique name space. To then create an instance of the class on a global variable somewhere else in a js file.

So in the case of a popup is it best to have it global or would it be best to create it on a rollover event and remove it on a rollout event.

//pseudo code
  $$('domelementClass').observe('mouseover', function(event) { 
      var popup= new em.components.grid.Popup(event.target);
   })

the issue I see with above is I have no reference to remove it on the rollout.

  $$('do开发者_高级运维melementClass').observe('mouseout', function(event) { 
     popup.remove();
   })


Namespacing has the same purpose of packaging, avoiding collision. As your example above shows, in JavaScript, you namespace functions and variables by making them properties of an object.

Does this mean in other classes I have access to the show method if I use the namespace path above.

// Another class in prototype em.components.grid.Popup.show();

In this case no because 'show()' is an instance method, it can only be called once you have a new Popup. You can use your namespaced Popup as an instance in another class or if you want to call show like a static method in Java then you would call Popup.prototype.show();

var Popup = Class.create({
    initialize: function(params){
        alert("I exist");
    },

    show:function(){
        alert("show!");
    }
});

// Popup.show(); // would error:

// Uncaught TypeError: Object function klass() {
//     this.initialize.apply(this, arguments);
//   } has no method 'show'

Popup.prototype.show();

foo = new Popup();

foo.show();

Some useful links:

http://michaux.ca/articles/javascript-namespacing

http://blog.anselmbradford.com/2009/04/09/object-oriented-javascript-tip-creating-static-methods-instance-methods/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜