没有调用Knockout viewmodel函数

时间:2017-02-16 16:52:09

标签: asp.net-mvc jquery-ui knockout.js

我正在使用我的_Layout.cshtml页面中引用的knockout(v3.2.0)和jQuery(v1.12.4)。我在ManageActivities.cshtml页面的javascript部分有一个名为cloneActivity的函数,该函数应该从下面粘贴的按钮标记触发。

<script type="text/javascript">
  $(function () {
    var employeeId = @ViewBag.UserInfo.UserId;

    function ActivityViewModel() {
      var self = this;
      self.ActivityHistoryId = ko.observable("");
      self.CompanyId = ko.observable("");
      self.UserId = ko.observable("");
      self.WorkFlowId = ko.observable("");
      self.ActivityName = ko.observable("");
      self.ActivityDescription = ko.observable("");
      self.Status = ko.observable("");

      var Activity = {
        ActivityHistoryId: self.ActivityHistoryId,
        CompanyId: self.CompanyId,
        UserId: self.UserId,
        WorkFlowId: self.WorkFlowId,
        ActivityName: self.ActivityName,
        ActivityDescription: self.ActivityDescription,
        Status: self.Status
      };

    self.Activity = ko.observable();
    self.ActivitiesArray = ko.observableArray();

    self.cloneActivity = function () {
      console.log('clone row clicked');
    };
  };

  var activityViewModel = new ActivityViewModel();
  ko.applyBindings(activityViewModel);
});
</script>

HTML按钮标记

<button class="btn btn-xs btn-success" title="clone work activity" name="cloneWork" data-toggle="modal" data-target="#addWorkInModal" data-bind="click: $root.cloneActivity"><i class="fa fa-clone"></i></button>

我没有看到任何错误,也没有调用该函数。我在按钮点击之前尝试了$ parent,$ parents [1],self,$ root和no。如果我将该函数移到ActivityViewModel之外并将该按钮更改为onclick =&#34; cloneActivity();&#34;我可以在控制台中看到该消息。

不确定我可能会遗漏什么,因为我在我的应用程序中的其他位置使用相同的概念。非常感谢任何帮助。

我桌子的标记......

<div class="panel-body">
  <table id="master" class="table table-striped table-hover table-condensed" cellspacing="0">
    <thead>
      <tr>
        <th class="rpt_col_bg_head" style="width: 3%;"></th>
        <th class="rpt_col_bg_head" style="width: 20%;">Result</th>
        <th class="rpt_col_bg_detail" style="width: 20%;">Work Activity</th>
        <th class="rpt_col_bg_detail" style="width: 180px;">Effort(%)</th>
        <th class="rpt_col_bg_detail" style="width: 7%;">Status</th>
        <th class="rpt_col_bg_detail" style="width: 30%;">Were there any innovations</th>
        <th class="rpt_col_bg_detail text-center" style="width: 7%;">Action</th>
     </tr>
    </thead>
  </table>
</div>

从服务器返回数据的ajax调用如下所示:

 var table = $('#master').DataTable({
   ajax : {
     type : "POST",
     url : "@Url.Action("GetAllActivities", "Activities")",
     data : { "UserId" : employeeId }
   },
   columns : [
     {  className : "details-control", orderable : false, defaultContent: "" },
     {  orderable : false, data : "ParentName" },
     {  orderable : false, data : "ActivityName" },
     {  orderable : false, data : "EffortHtml" },
     {  orderable : false, data : "Status" },
     {  orderable : false, data : "Innovation" },
     {  orderable : false, data : "ActionButtons" }
   ],
   columnDefs : [{
     targets: [6],  //disable search and sort on Actions column
     searchable : false,
     orderable : false
   }]
});  

我捕获xhr以将返回的JSON保存到我的视图模型中,淘汰赛正在观察。

table.on('xhr', function () {
  var json = table.ajax.json();
  self.ActivitiesArray.push(json.data);  // Initialize the view-model
  console.log(ko.toJSON(self.ActivitiesArray));
});    

这是返回的JSON,其中包含附加了ID的按钮的标记。

[[{"ActivityHistoryId":1,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 1","ActivityDescription":"Description of Test Activity 1","Status":"<span class='badge badge-blue'>Not Started</span>","Effort":25,"EffortHtml":"<span id='originalEffort1'>25</span><button class='btn btn-xs text-primary' style='background: none; margin-bottom: 5px;' title='edit effort' onclick='showEdit(25);'><i class='fa fa-pencil'></i></button><section id='editEffort25' class='edit bg-warning edit-box' style='display: none;'><div style='margin-top: 5px;'><label class='text-muted'>Adjust Effort(%) </label><input type='number' min='1' max='200' class='effort' id='adjustedEffort1' style='width: 100%;'></div><small id='enterEffortMsg1' class='error-effort text-danger display: none;'></small><div style='margin-top: 5px;'><label class='text-muted'>Total Annual Effort(%) </label><input type='number' class='total_effort text-muted' id='totalEffort25' value='' disabled='' style='width: 100%;'></div><div class='total_after_adjust text-danger' style='margin-top: 15px;'></div><div id='totalAfterAdjustmentDiv1' class='total_after_adjust text-danger' style='margin - top: 15px; display: none;'><label id='totalAfterAdjustment1'><small></small><br></label></div><div style='margin-top: 5px;' class='text-center'><button onclick='checkEditEffort(1);' class='btn btn-info btn-xs' title='check total annual effort after adjust'>Check</button><button onclick='saveEditEffort(1);' class='btn btn-primary btn-xs' style='margin-left: 5px;'>Save</button><button onclick='showEdit(25);' class='btn btn-default btn-xs' style='margin-left: 5px;'>Cancel</button></div><div id='saveSuccess1' class='alert alert-success' style='display:none; margin-top: 10px; margin-bottom: 0;'><i class='fa fa-check'> Update Success!</i></div><div class='alert alert-danger' style='display:none; margin-top: 10px; margin-bottom: 0;'></div></section>","Innovation":false,"ParentId":2,"ParentName":"Test Result 1","ActionButtons":"<td><div class='text-center'><ul class='list-inline'><li><button class='btn btn-xs btn-primary' title='edit work activity' name='editWork' onclick='editActivity(1);'><i class='fa fa-pencil'></i></button></li><li><button class='btn btn-xs btn-danger' title='delete work activity' name='deleteWork' data-toggle='modal' data-target='#confirm_modal' onclick='deleteActivity(1);'><i class='fa fa-remove'></i></button></li><li><button class='btn btn-xs btn-success' title='clone work activity' name='cloneWork' data-bind='click: $root.cloneActivity'><i class='fa fa-clone'></i></button></li></ul></div></td>"},{"ActivityHistoryId":2,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 2","ActivityDescription":"Description of Test Activity 2","Status":"<span class='badge badge-blue'>Not Started</span>","Effort":9,"EffortHtml":"<span id='originalEffort2'>9</span><button class='btn btn-xs text-primary' style='background: none; margin-bottom: 5px;' title='edit effort' onclick='showEdit(9);'><i class='fa fa-pencil'></i></button><section id='editEffort9' class='edit bg-warning edit-box' style='display: none;'><div style='margin-top: 5px;'><label class='text-muted'>Adjust Effort(%) </label><input type='number' min='1' max='200' class='effort' id='adjustedEffort2' style='width: 100%;'></div><small id='enterEffortMsg2' class='error-effort text-danger display: none;'></small><div style='margin-top: 5px;'><label class='text-muted'>Total Annual Effort(%) </label><input type='number' class='total_effort text-muted' id='totalEffort9' value='' disabled='' style='width: 100%;'></div><div class='total_after_adjust text-danger' style='margin-top: 15px;'></div><div id='totalAfterAdjustmentDiv2' class='total_after_adjust text-danger' style='margin - top: 15px; display: none;'><label id='totalAfterAdjustment2'><small></small><br></label></div><div style='margin-top: 5px;' class='text-center'><button onclick='checkEditEffort(2);' class='btn btn-info btn-xs' title='check total annual effort after adjust'>Check</button><button onclick='saveEditEffort(2);' class='btn btn-primary btn-xs' style='margin-left: 5px;'>Save</button><button onclick='showEdit(9);' class='btn btn-default btn-xs' style='margin-left: 5px;'>Cancel</button></div><div id='saveSuccess2' class='alert alert-success' style='display:none; margin-top: 10px; margin-bottom: 0;'><i class='fa fa-check'> Update Success!</i></div><div class='alert alert-danger' style='display:none; margin-top: 10px; margin-bottom: 0;'></div></section>","Innovation":false,"ParentId":2,"ParentName":"Test Result 1","ActionButtons":"<td><div class='text-center'><ul class='list-inline'><li><button class='btn btn-xs btn-primary' title='edit work activity' name='editWork' onclick='editActivity(2);'><i class='fa fa-pencil'></i></button></li><li><button class='btn btn-xs btn-danger' title='delete work activity' name='deleteWork' data-toggle='modal' data-target='#confirm_modal' onclick='deleteActivity(2);'><i class='fa fa-remove'></i></button></li><li><button class='btn btn-xs btn-success' title='clone work activity' name='cloneWork' data-bind='click: $root.cloneActivity'><i class='fa fa-clone'></i></button></li></ul></div></td>"},{"ActivityHistoryId":3,"UserId":91,"WorkFlowId":4,"ActivityName":"Test Activity 3","ActivityDescription":"Description of Test Activity 3","Status":"<span class='badge badge-lightBlue'>In Progress</span>","Effort":12,"EffortHtml":"<span id='originalEffort3'>12</span><button class='btn btn-xs text-primary' style='background: none; margin-bottom: 5px;' title='edit effort' onclick='showEdit(12);'><i class='fa fa-pencil'></i></button><section id='editEffort12' class='edit bg-warning edit-box' style='display: none;'><div style='margin-top: 5px;'><label class='text-muted'>Adjust Effort(%) </label><input type='number' min='1' max='200' class='effort' id='adjustedEffort3' style='width: 100%;'></div><small id='enterEffortMsg3' class='error-effort text-danger display: none;'></small><div style='margin-top: 5px;'><label class='text-muted'>Total Annual Effort(%) </label><input type='number' class='total_effort text-muted' id='totalEffort12' value='' disabled='' style='width: 100%;'></div><div class='total_after_adjust text-danger' style='margin-top: 15px;'></div><div id='totalAfterAdjustmentDiv3' class='total_after_adjust text-danger' style='margin - top: 15px; display: none;'><label id='totalAfterAdjustment3'><small></small><br></label></div><div style='margin-top: 5px;' class='text-center'><button onclick='checkEditEffort(3);' class='btn btn-info btn-xs' title='check total annual effort after adjust'>Check</button><button onclick='saveEditEffort(3);' class='btn btn-primary btn-xs' style='margin-left: 5px;'>Save</button><button onclick='showEdit(12);' class='btn btn-default btn-xs' style='margin-left: 5px;'>Cancel</button></div><div id='saveSuccess3' class='alert alert-success' style='display:none; margin-top: 10px; margin-bottom: 0;'><i class='fa fa-check'> Update Success!</i></div><div class='alert alert-danger' style='display:none; margin-top: 10px; margin-bottom: 0;'></div></section>","Innovation":true,"ParentId":5,"ParentName":"Test Result 2","ActionButtons":"<td><div class='text-center'><ul class='list-inline'><li><button class='btn btn-xs btn-primary' title='edit work activity' name='editWork' onclick='editActivity(3);'><i class='fa fa-pencil'></i></button></li><li><button class='btn btn-xs btn-danger' title='delete work activity' name='deleteWork' data-toggle='modal' data-target='#confirm_modal' onclick='deleteActivity(3);'><i class='fa fa-remove'></i></button></li><li><button class='btn btn-xs btn-success' title='clone work activity' name='cloneWork' data-bind='click: $root.cloneActivity'><i class='fa fa-clone'></i></button></li></ul></div></td>"}]]  

2 个答案:

答案 0 :(得分:0)

applyBindings渲染完成后,您需要致电table

您可以使用init.dt事件代替xhr

table.on('init.dt', function (e, settings, json) {
  self.ActivitiesArray.push(json.data);  // Initialize the view-model
  console.log(ko.toJSON(self.ActivitiesArray));

  // call bindings here
  ko.applyBindings(activityViewModel);
}); 

修改

如果table取决于activityViewModel, 然后你可以在主脚本函数中保留applyBindings并在重新应用之前清理dom

table.on('init.dt', function (e, settings, json) {
  self.ActivitiesArray.push(json.data);  // Initialize the view-model
  console.log(ko.toJSON(self.ActivitiesArray));

  // clean the dom since we already applied bindings
  ko.cleanNode(document.body);

  // re apply bindings here
  ko.applyBindings(activityViewModel);
}); 

答案 1 :(得分:0)

您没有调用IIFE,并且您之前使用的是jQuery $符号。它应该有下面的表格。或者你可以省略jQuery声明,因为你没有在IIFE中使用它。

(function($){
    // stuff
})(jQuery);

您的代码缺少调用表达式的最后一对括号。

我不确定$(function(){});构造的行为方式,但事实证明这是调用$(document).ready(function(){});的快捷方式。我没有使用该快捷方式,并会像这样构建代码:

关闭正文标记前的

_Layout.cshtml:

// load jQuery and knockoutJS here
@RenderSection("scripts", required: false)

在您的页面上:

@section scripts
{
    <script>
        (function($, ko) {

            // stuff

            $(document).ready(function() {
                var activityViewModel = new ActivityViewModel();
                ko.applyBindings(activityViewModel);
            });

        })(jQuery, ko);
    </script>
}