【问题标题】:Call an existing method inside viewmodel在视图模型中调用现有方法
【发布时间】:2015-02-10 12:19:55
【问题描述】:

我想知道是否可以在视图模型的另一个方法中调用一个方法

在我的附加:函数中,我有一个显示所有客户的 ajax 方法

           attached: function () {
            $.ajax({
                type: "GET",
                url: "/api/listusers/GetContractorList",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                headers: appsecurity.getSecurityHeaders(),

                success: function (result) {
                    if (result != null) {
                        var mappedContractorList = $.map(result, function (item) {
                            return new GKContractorObj(item);
                        });

                        viewmodel.ContractorList(mappedContractorList);

                        tableObj = $('#tblContractorsList').DataTable();

                    }
                },
                failure: function (error) {
                    logger.logError('Failed to contractor list', 'Error', null, true);
                }
            })

我想调用里面的方法attached:function in another data-bind method out here

showGKContractors: 
    function () {
                //Some Logic 
                //Call to  url (attached:method): "/api/listusers/GetContractorList" 
                (without having to rewrite code)
               }

我该如何解决这个问题?

【问题讨论】:

    标签: ajax mvvm knockout.js jquery-datatables


    【解决方案1】:

    是的!只需将您想要在多个位置调用的附加代码部分移动到一个对您的两个视图模型都可见的全新函数中,例如

    makeAjaxRequest: function () {
       ///1. the code you want to move from inside your attached function
    }
    

    然后调用你的附加函数和你的 showGkContractors 的新函数

    attached: function () {
    
        makeAjaxRequest();
       ///2. all the other code you don't want to move from attached
    }
    
    showGKContractors: function () {
    
                //1. Some Logic 
                //2. makeAjaxRequest();
    
               }
    

    如果 attach 和 showGKContractors 都在同一个 .js 文件中,则可以在页面顶部定义新函数,或者您可以将其放在单独的脚本文件中并根据需要通过命名空间引用它

    例如,在您的 GKContractors 上方网页中包含的单独文件中,附加文件中包含此脚本的文件

     (function (scope) {
    
    scope.makeAjaxRequest: function () {
           ///1. the code you want to move from inside your attached function
           ///2. all the other code you don't want to move
        }
    
    })(window.SharedNameSpace);
    

    然后在您附加的和 showGKContractors 文件中,您可以调用 makeAjaxRequest 函数 通过调用

    window.SharedNameSpace.makeAjaxReuest();
    

    【讨论】:

      【解决方案2】:

      使用共享逻辑的最佳做法是将其从视图模型中移出,并将其放入两个视图模型都可以使用的共享类中。

      如果您实际上是在尝试在另一个视图模型中触发某些内容,那么您应该使用事件或消息来执行此操作。有几个库支持这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-04
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-18
        相关资源
        最近更新 更多