2012-10-31 72 views
3

這是我的代碼。knockoutJS,觸發事件,但event.which仍未定義

<input type="text" placeholder="Add New Tag" data-bind="value: tagToAdd, valueUpdate: 'afterkeydown', event: { keypress: addOnEnter }" /> 

這是我的淘汰賽碼。

self.addOnEnter = function (event) { 

     console.log(event.which); 

     var keyCode = (event.which ? event.which : event.keyCode); 
     if (keyCode === 13) { 
      self.addTag(); 
     } 
     return true; 
    }; 

當我在輸入字段中輸入某些內容時,我記錄了事件,不斷得到未定義的事件。我不知道爲什麼我無法捕捉哪個事件被解僱。

你可以在jsFiddle上測試我的代碼。 http://jsfiddle.net/GBLNR/6/

只需在輸入字段中輸入任何內容,然後從控制檯觀看結果。

回答

4

Knockout將當前數據上下文作爲第一個參數傳遞給處理函數。 event是第二個參數。

所以,你的函數的簽名必須是:

self.addOnEnter = function(data, event) { 

} 

另外,處理一個很好的辦法是通過使用自定義的綁定:

//a custom binding to handle the enter key (could go in a separate library) 
ko.bindingHandlers.enterKey = { 
    init:function (element, valueAccessor, allBindingsAccessor, data, context) { 
     var wrappedHandler, newValueAccessor; 

     //wrap the handler with a check for the enter key 
     wrappedHandler = function (data, event) { 
      if (event.keyCode === 13) { 
       valueAccessor().call(this, data, event); 
      } 
     }; 

     //create a valueAccessor with the options that we would want to pass to the event binding 
     newValueAccessor = function() { 
      return { keyup:wrappedHandler }; 
     }; 

     //call the real event binding's init function 
     ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data, context); 
    } 
}; 

現在你只想用這enterKey綁定您的addOnEnter函數,它只需要處理您的數據。

+0

非常感謝你,沒辦法,我可以搞清楚自己。 – qinking126

0

修改了Niemeyer對下面代碼的回答,以防止Enter鍵事件冒泡。當您想要避免textarea元素中的換行符時有用。

ko.bindingHandlers.enterPressed = { 
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) { 
    // Wrap the handler with a check for the enter key. 
    var wrappedHandler = function (data, event) { 
     if (event.keyCode === 13) { 
     valueAccessor().call(this, data, event); 
     return false; 
     } else { 
     return true; // Allow event to bubble. 
     } 
    }; 

    // Create a valueAccessor with the options that we would want to pass to the event binding. 
    var newValueAccessor = function() { 
     return { keypress: wrappedHandler }; // Using keypress instead of keyup. 
    }; 

    // Call the real event binding's init function. 
    ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, viewModel); 
    } 
};