直接调用jQuery事件处理函数Generate时如何传递数据?
Great question! I’ve run into this exact scenario before—when you’re used to relying on jQuery’s event.data for event-bound calls, direct function invocations can feel tricky at first. Let’s cover two solid approaches to solve this:
1. Simulate jQuery’s Event Object Structure
Since your Generate function expects an event parameter with a data property, you can directly pass a mock event object that matches this structure when calling the function manually:
var objKeyboard = { init: function( config ) { this.config = config; this.bindEvents(); // Direct call with simulated event object this.Generate({ data: { idx: 2 } }); }, bindEvents: function() { this.config.selectedKey.on('change', { idx: 1 }, this.Generate); }, Generate: function(event) { alert(event.data.idx); // Will alert 2 for the direct call, 1 for the event trigger } }; objKeyboard.init({ selectedKey: $("#selected_key_b"), });
This works because you’re mirroring the exact structure jQuery passes to your handler when the event fires—no changes needed to your existing Generate logic.
2. Refactor for Flexible Usage (Recommended)
If you want your Generate function to work seamlessly both as a jQuery event handler and as a standalone function, refactor it to accept optional direct parameters:
var objKeyboard = { init: function( config ) { this.config = config; this.bindEvents(); // Direct call with explicit idx parameter this.Generate(null, 2); }, bindEvents: function() { // Bind with event.data as before this.config.selectedKey.on('change', { idx: 1 }, this.Generate); }, Generate: function(event, customIdx) { // Use customIdx if provided, otherwise fall back to event.data.idx var idx = customIdx || (event ? event.data.idx : 0); alert(idx); // Alerts 2 for direct call, 1 for event trigger } }; objKeyboard.init({ selectedKey: $("#selected_key_b"), });
This approach makes your function more versatile—you can call it with or without the event context, and it’ll handle both cases gracefully.
Why Your Original Direct Call Didn’t Work
When you tried this.Generate({ idx: 2 }), your function was looking for event.data.idx, but your passed object only had event.idx. jQuery wraps your data in the data property of the event object when binding, so you need to match that structure (or refactor to avoid the dependency).
内容的提问来源于stack exchange,提问作者Gaz

