【问题标题】:Knockout js root bindingKnockout js 根绑定
【发布时间】:2017-04-17 22:22:59
【问题描述】:

我无法在此特定页面上使用 $root 访问方法。此代码适用于我的其他页面,但我不明白。我每页有一个视图模型。它找不到 removeAttachment。

knockout-3.4.0.js:72 Uncaught TypeError: Unable to process binding "click: function (){return $data.bind.removeAttachment($data,event,$index) }" 消息:无法读取未定义的属性“removeAttachment”

var model = function AppViewModel(){
self.removeAttachment = function(data, event, attachmentClicked){
    fileNameToDelete = attachmentClicked;
    $("deleteText").append(" " + attachmentClicked + "?");
     $('#delete-confirm').modal('show'); 
};
};
 var app = new model();
ko.applyBindings(app, document.getElementById("panel"));
 <div id="panel">

<tbody class="types">
<!-- ko foreach: multiFileData().fileArray -->
<tr>
<td><span class="attachName" data-bind="text:name"></span></td>
<td><span class="attachName" data-bind="$parent.sizeInMB: size"></span></td>
<td id="remove" class="glyphicon glyphicon-trash" data-toggle="modal" data-target="delete-confirm" 
data-bind="click:$root.bind.removeAttachment($data, event, $index)"> </td>
</tr>
<!-- /ko -->
</tbody>
</div>

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    你可能想要:

    click: $root.removeAttachment
    

    如果需要传入额外的参数:

    click: $root.removeAttachment.bind($root, $index)
    

    传递给函数的第一个和第二个参数将始终是$dataevent。使用bind,您可以将它们推回并传入新的第一个参数(以及设置this 值)。

    您还需要确保 removeAttachment 实际设置在视图模型中。

    var model = function AppViewModel() {
        var self = this;
        self.removeAttachment = ...
    };
    

    【讨论】:

    • 试试这个: 不能与 $root.removeAttachment 一起使用
    • 我扩展了我的答案,
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签