Knockout 事件传递参数的方法

来源:互联网 发布:js怎么截取地址字符串 编辑:程序博客网 时间:2024/06/14 03:24

   在Knockout中直接使用函数传递参数是不行的,会导致函数在初始化时就被调用,例如:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;"><div data-bind="click:changeEditor($index)"></div>  
  2. </span>  
       将导致函数在初始化时,点击事件changeEditor()函数就被调用,显然,违背初衷。

        要实现参数的传递,有2种方法:

1、方法一:使用函数包裹

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <div data-bind="event: { click: function(data, event) {changeEditor('param1', 'param2', data, event) } }">  
  2.     Mouse over me  
  3. </div>  

点击事件响应函数又套了一层,调用chageEditor函数,在原changeEditor()函数调用中传入参数。


2、方法二:使用bind函数

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <button data-bind="event: { click: changeEditor.bind($data, 'param1', 'param2') }">  
  2.     Click me  
  3. </button>  

使用该方式传递参数时,$data为形式化写法,不能改变,后面可带若干参数,如param1,param2等。

3、缺省的参数传递

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <div data-bind="event: { mouseover: myFunction }">  
  2.     Mouse over me  
  3. </div>  
  4.    
  5.  <script type="text/javascript">  
  6.     var viewModel = {  
  7.         myFunction: function(data, event) {  
  8.             if (event.shiftKey) {  
  9.                 //do something different when user has shift key down  
  10.             } else {  
  11.                 //do normal action  
  12.             }  
  13.         }  
  14.     };  
  15.     ko.applyBindings(viewModel);  
  16. </script>  
        即使绑定定义中函数不带任何参数,data和event两个参数总会被缺省传递,data指当前的viewModel对象,event为事件对象。

注意:在bind方式传递参数时,data和event两个参数依然被缺省传递,新加入的参数,在使用时排在第一位,例如,进行下面的定义:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;"><div data-bind="click:changeEditor.bind($data,$index)"></div></span>  
在使用时,index 为第一个参数。

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. function changeEditor(index,data, event){  
  2.     alert('参数:'+ index + ',' + data+ "," + event);  
  3.     alert(arguments.length);  
  4.   
  5.      var tmp = data;  
  6.      tmp.headerText = 'OK!!!';  
  7.      tmp.editing = true;  
  8.     // columns2[idx](tmp);  
  9. }  

0 0