How to run a JavaScript function that is inside a namespace
If I had something like:
App = {
editingMode: function ()
{
function setEditingMode(entityID) {
$开发者_C百科('#editingMode').val('1');
$.ajax({
type: "POST",
url: "/Organisations/Manage/LockEntity/",
data: "entityID=" + entityID
});
}
function setEditingModeOff(entityID) {
if ($("#myform").valid() == true)
{
$('#editingMode').val('0');
$.ajax({
type: "POST",
url: "/Organisations/Manage/UnlockEntity/",
data: "entityID=" + entityID
});
}
}
}
};
How would I run one of the inner functions?
App.editingMode();
but then what would I do to get at the setEditingMode
??
You can use a different structure to accomplish what you want. I don't know if it would break something else you are using, so I'll just give you an example. I'm not sure this is the actual solution, please take a look and tell me if that's not what you need. If you use:
var App = {
editingMode:
{
setEditingMode: function(entityID) {
$('#editingMode').val('1');
$.ajax({
type: "POST",
url: "/Organisations/Manage/LockEntity/",
data: "entityID=" + entityID
});
},
setEditingModeOff: function(entityID) {
if ($("#myform").valid() == true)
{
$('#editingMode').val('0');
$.ajax({
type: "POST",
url: "/Organisations/Manage/UnlockEntity/",
data: "entityID=" + entityID
});
}
}
}
};
you can call editingMode's methods like this:
App.editingMode.setEditingModeOff(1);
Notice that they will still be encapsulated within App, you don't necessarily move them to the global scope.
You would need to return a reference to one or otherwise make it accessible from outside of the function, for example, attaching it to window
(effectively making it a global) or the App
object.
Although the answer given by 'Nikoloff' enables you to call those functions but I would point out to bit different (and probably better) approach. Following 'Module' pattern concept will not just solve your problem effectively but also allow you to have private variables. (Search for 'Module pattern in Javascript' and it will give you loads of online resources.)
App = {
editingMode: function ()
{
// Below var is no way directly accessible and act as private var
var privateVar =5;
// Below function is going to give access to private var
function getPrivateVar(){
return privateVar;
}
//Your functions - untouched
function setEditingMode(entityID) {
$('#editingMode').val('1');
$.ajax({
type: "POST",
url: "/Organisations/Manage/LockEntity/",
data: "entityID=" + entityID
});
}
function setEditingModeOff(entityID) {
if ($("#myform").valid() == true)
{
$('#editingMode').val('0');
$.ajax({
type: "POST",
url: "/Organisations/Manage/UnlockEntity/",
data: "entityID=" + entityID
});
}
}
return {
setEditingMode: setEditingMode,
setEditingModeOff: setEditingModeOff,
getPrivateVar: getPrivateVar
}
}
};
App.editingMode().setEditingMode();
console.log(App.editingMode().getPrivateVar());
精彩评论