我有一个这样的Javascript对象:
function App(callback){
// Call some "long running functions meant for initialization
callback(this);
}
在我的主模板页面(_Layout。我像这样实例化它:
_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... }); //???
感谢洛伦佐
你的跑步模式很有趣。我建议使用一种更低调的方式来初始化和调用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
借来从这里:
var isFunction = function(functionToCheck)
{
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}