Reputation: 11384
I have an object/function/closure (I think it's all three?) and I need to apply separate instances of it to multiple elements on the page.
var NS = NS || {};
NS.PLAJAX = function(){
var pub = {};
var self = this;
pub.Init = function(FormRef){
// do stuff
};
self.aPrivateFunction = function(){
// do stuff
}
return pub;
}();
// Apply a *copy* to each element with the given class
$(function(){
$('.el-form-wrapper').each(function(index, Element){
// Attempt #1
NS.PLAJAX.Init(Element); // Doesn't make copies!
//OR, Attempt #2
var Newbie = new NS.PLAJAX(); // Throws a "not a constructor" error
Newbie.Init(Element);
});
});
How can I get a new instance of this closure/object on each element?
Upvotes: 0
Views: 82
Reputation: 10378
i have tried this and it works for me hope this will work for u
var NS = NS || {};
NS.PLAJAX = function(){
var pub = {};
var self = this;
pub.Init = function(FormRef){
alert(FormRef);
};
self.aPrivateFunction = function(){
alert("private");
}
return pub;
};
// access the object NS
$(function(){
$('.el-form-wrapper').each(function(index, Element){
var a=NS.PLAJAX();
console.log(typeof(a));
a.Init("gg"); // Doesn't make copies!
//OR, Attempt #2
var Newbie = new NS.PLAJAX(); // Throws a "not a constructor" error
Newbie.Init("ff");
});
});
see demo
Upvotes: 0
Reputation: 10377
What you've got is just an object. However, to use the new
keyword, you want a function (a constructor).
There is no need to return anything from a constructor. The new
keyword creates a new object, calls the function with that new object as this
, and then returns it. Public methods should be assigned to properties of this
(self
) and private methods should be local variables. What you'll end up with is something like this:
var NS = NS || {};
NS.PLAJAX = function(){
var self = this;
self.Init = function(FormRef){
// do stuff
};
var aPrivateFunction = function(){
// do stuff
}
};
// Apply a *copy* to each element with the given class
$(function(){
$('.el-form-wrapper').each(function(index, Element){
var Newbie = new NS.PLAJAX();
Newbie.Init(Element);
});
});
Upvotes: 2