Here is my code structure, that I saw from someone else and am trying to make sense of it. I believe its a closure style and not a plugin style? maybe someone can clarify this for me if its a closure style.
Kind of plugin style. Here are some general questions.
- So the variable NP is in the global namespace correct? and just used
as a reference to the closure and its inner public methods. - Using NP (which is the namespace ) before a method is just a way to
reference that method from outside the closure. - If I set NP to null does it destroy and allow for garbage collection
of everything inside of NP including all variables.
This is the bigger question here so I’ll put it out on its own.
When I trigger an event from an inner method actionMethod()
I want to be able to receive that event, from lets say another js file. For example home.js
home.js
$(function(){
NP.bind("CHANGED", event_handler);
function event_handler(evt, data ){
// do something....
}
$('#button').click(function(){
// call my public method in my NP plugin
NP.PublicMethod();
});
});
Closure ( style )
var NP = function(namespace){
var innerVariable = "the outside scope can't here me";
finction innerMethod(){
//does some inner functionality to the closure
}
namespace.PublicMethod = function(){
// does some calling of inner function.
// user can access this method from the myplugin directly.
// example: NP.PublicMethod();
}
function actionMethod(){
// trigger an event so others outside this closure can react
namespace.trigger("CHANGED");
}
}(NP || {});
Please if someone can answer the first 3 questions then the larger question about the triggering of events. Thanks in advance
Update:
Something that ShankarSangoli made an example of by triggering the event from a DOM element.
The issue here is I have a dom element that is acting as a close button inside my closer, but home.js has no idea of it or no reference to, nor should it. So I need a way for to listen on the NP object level for events fired from it. As a test I tried the below code and it worked. No idea why as its not a DOM element, but in most languages you can fire an event from most generic objects. And in this case NP is in fact an object, or am I going mad in thinking its an object.
closure Object
function actionMethod(){
// trigger an event so others outside this closure can react
$(namespace).trigger("CHANGED");
}
home.js
$(TWCCP).bind("CLOSED_POPUP", onClosePopup);
Now I’m very confused about this. How is this possible now???
NPis in global namespace.NP.methodName();NP = nullthen it will be destroyed and javascript will take care of garbage collection and destroying it inner variable.You cannot use
NP.bindunlessNPis a jquery object associated to a dom element.The way to trigger any event is as below
For your last part of question try this
Closure(style)
home.js