如何使用asp.net mvc和knockoutjs构建对javascript函数的动态调用
我正在构建一个mvc应用程序,将其用作模板HotTower(你知道,durandal、knockout、breeze等)。应用程序尚未准备就绪,我们正在取得良好进展:)。 在一个函数的中间,我需要构建一个对javascript函数的动态调用。 使用硬代码值的调用类似于:如何使用asp.net mvc和knockoutjs构建对javascript函数的动态调用,javascript,asp.net-mvc,knockout.js,hottowel,Javascript,Asp.net Mvc,Knockout.js,Hottowel,我正在构建一个mvc应用程序,将其用作模板HotTower(你知道,durandal、knockout、breeze等)。应用程序尚未准备就绪,我们正在取得良好进展:)。 在一个函数的中间,我需要构建一个对javascript函数的动态调用。 使用硬代码值的调用类似于: <a href="#" id="openreport" onclick="showReport('@Url.Action("
<a href="#" id="openreport"
onclick="showReport('@Url.Action("Index","Report", new { Id= 9, languageId = 2})');">Show
report</a>
上面的电话很好用。当我尝试使用knockoutjs将onclick事件绑定到string属性时,问题就开始了。大概是这样的:
<a href="#" id="openReport" data-bind="onclick: $root.reportUrl()" >
Show report
展示报告
其中报告url是一个可观察变量。下面是typescript代码:
export var reportUrl =<any> ko.observable();
export var expandRow = function (myObjectComeFromATable) {
var urlAction = '@Url.Action("Index", "Report", new { Id= ID_TO_REPLACE, languageId = LANG_TO_REPLACE }) ';
var url = "showReport('"+urlAction+"');";
reportUrl(url);
};
export var reportUrl=ko.observable();
export var expandRow=函数(myObjectComeFromATable){
var urlAction='@Url.Action(“Index”,“Report”,new{Id=Id_TO_REPLACE,languageId=LANG_TO_REPLACE});
var url=“showReport(“+urlAction+”);”;
报告url(url);
};
更新
使用引号是可以的。敲除变量的值与之前显示的硬代码值相同。也许这是我的sintaxis在布局中的一个问题?您试图以可观察的方式评估代码?我认为这行不通。您可以在函数中手动执行评估。但我认为这不是一个好的解决方案 如果总是在单击时调用“showReport”,则不需要评估:只需在模型中具有包含要调用的url的属性,并在回调函数中运行showReport(yourUrl) 如果正在调用的函数发生更改,则可以在模型中保留对要调用的函数的引用。类似的(但更干净):
var模型=函数(){
var_this=这个;
this.function1=函数(){
警惕(“你好”);
}
this.function2=函数(){
警惕(“世界”);
}
this.run=函数(){
_这个。当前();
}
this.change=函数(){
_this.current=_this.function2;
}
this.current=this.function1;
}
应用绑定(新模型());
请看这里:
var model = function() {
var _this = this;
this.function1 = function() {
alert('hello');
}
this.function2 = function() {
alert('world');
}
this.run = function() {
_this.current();
}
this.change = function() {
_this.current = _this.function2;
}
this.current = this.function1;
}
ko.applyBindings(new model());
<a href="#" data-bind="click: run">Click</a>
<a href="#" data-bind="click: change">Switch</a>