我有这样的Javascript对象:
function App(callback){
// Call some "long running functions meant for initialization
callback(this);
}
在我的主模板页面(ASP MVC上的_Layout.cshtml)中,我将其设置为:
_Layout.cshtml
var oApp = new App(function(initializedApp){
// Instanciate here other Javascript components that depend on
// App initialization
var oComponent1 = new Component1(initializedApp);
});
这很好用!应用程序完成初始化后,Component1初始化,一切正常。
Page1.cshtml中出现问题(在_Layout.cshtml中呈现并且可以访问oApp)。 Page1还必须初始化自己需要完全初始化App的组件。
Page1.cshtml
// How do I "subscribe to the App callback function so that Compnent2, s
// specific to the Page1.cstml, is initialized afetr App has finished
// its initialization ???
var oComponent2 = new Compnent2(oApp);
oApp.callback(); // ???
oApp(function(initializedApp){ // code here... }); //???
由于
洛伦佐
答案 0 :(得分:0)
你的运行有趣的模式。我建议使用更不引人注目的方式初始化和调用javascript。我想说CSHTML中的大多数JS调用都可以被认为是代码味道。
无论如何,我会回答你的问题。我会更改App
以便能够注册回调:
function App(callbacks)
{
var self = this;
self.callbacks = [];
self.addCallbacks = function(newCallbacks)
{
//allow either a single callback or an array of callbacks
if(isFunction(callbacks)
{
self.callbacks.push(newCallbacks); //single callback
}
else
{
for(var i = 0; i < newCallbacks.length; i++)
{
//theoretically, you can have multi-dimensional arrays of callbacks, but that's just excessive
self.addCallbacks(newCallbacks[i]);
}
}
};
self.addCallbacks(callbacks);
//some point later, call all the callbacks:
for(var i = 0; i < self.callbacks.length; i++)
{
self.callbacks[i](this);
}
}
然后,在Page1.cshtml
:
var oComponent2 = new Compnent2(oApp);
var mycallback = function(initializedApp){ // code here... };
oApp.addCallbacks(mycallback);
//or, if you have many callbacks to register:
var mycallbacks = [
function(initializedApp){ // code here... },
function(initializedApp){ // code here... }
];
oApp.addCallbacks(mycallbacks);
isFunction
借鉴here:
var isFunction = function(functionToCheck)
{
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}