【问题标题】:how to build dynamic call to javascript function using asp.net mvc and knockoutjs如何使用asp.net mvc和knockoutjs构建对javascript函数的动态调用
【发布时间】:2013-07-10 14:08:17
【问题描述】:

我正在使用 HotTowel 模板构建一个 mvc 应用程序(你知道,durandal、knout、breeze 等)。该应用程序尚未准备好,但我们正在取得良好进展:)。 在一个功能的中间,我需要构建一个对 javascript 函数的动态调用。 使用硬编码值的调用类似于:

<a href="#" id="openreport"                                                 
onclick="showReport('@Url.Action("Index","Report", new { Id= 9, languageId = 2})');">Show  
report</a>

上面的调用工作正常。当我尝试使用 knockoutjs 将 onclick 事件绑定到字符串属性时,我的麻烦就开始了。像这样:

<a href="#" id="openReport" data-bind="onclick: $root.reportUrl()"  > 
 Show report                                                

在哪里报告 url 它是一个可观察的变量。这里是打字稿代码:

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);   
};

更新 使用引号很好。淘汰变量的值与之前显示的硬代码值相同。也许是我的 sintaxis 布局有问题?

【问题讨论】:

    标签: javascript asp.net-mvc knockout.js hottowel


    【解决方案1】:

    您正在尝试评估 observable 中的代码?我不认为它会起作用。您可以在函数中手动执行 eval。但我认为这不是一个好的解决方案。

    如果您总是在点击时调用“showReport”,则不需要 eval:只需在模型中有一个包含要调用的 url 的属性,然后在回调函数中运行 showReport(yourUrl)。

    如果您在点击时调用的函数发生变化,您可以保留对要在模型中调用的函数的引用。类似的东西(但更干净):

    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>
    

    请看这里:http://jsfiddle.net/pp2QA/2/

    【讨论】:

      猜你喜欢
      • 2012-10-19
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多