[英]Event handler in object literal not firing
我正在創建一個Wordpress插件,並且已經創建了一個對象常量,我想在其中封裝我的所有邏輯,但是似乎無法觸發事件處理程序。
我正在使用jQuery 1.7.1
首先,我有通過php創建的數據行:
<div class="table-wrapper">
<?php
global $wpdb;
$students = $wpdb->get_results("SELECT studentID, lname, fname, email FROM student");
foreach($students as $student) : ?>
<div class="row" id="<?php echo $student->studentID; ?>" >
<div class="last_name">
<h4><?php echo __($student->lname); ?></h4>
</div>
<div class="first_name">
<h4><?php echo __($student->fname); ?></h4>
</div>
<div class="phone">
<h4><?php echo __($student->phone); ?></h4>
</div>
<div class="email">
<h4><?php echo __($student->email); ?></h4>
</div>
</div><!-- /row -->
<?php endforeach; ?>
<div id="new">
<button id="new_student"><?php echo __('Add New Student'); ?></button>
</div>
</div><!-- /table-wrapper -->
這是我的javascript / jquery文件:
var Student = {
init: function(config) {
this.config = config;
this.isDisplayed = false;
console.log('in init'); // this fires upon instantiation
this.bindEvents();
},
bindEvents: function(){
console.log('in bind'); // this fires upon instantiation
this.config.studentSelection.on('click', '.row', this.config.fetchStudentDetails);
console.log('after'); // this does NOT fire
},
fetchStudentDetails: function() {
var self = Student;
alert('in event'); // this does NOT fire
}
};
Student.init({
studentID: jQuery('.row').attr('id'),
studentSelection: jQuery('.table-wrapper')
});
我嘗試了一些小變化,例如將'.row'傳遞給studentSelection變量,然后嘗試直接在bindEvents方法中將事件處理程序與其綁定:
bindEvents: function(){
console.log('in bind'); // this fires upon instantiation
this.config.studentSelection.on('click', this.config.fetchStudentDetails);
console.log('after'); // this does NOT fire
},
Student.init({
studentID: jQuery('.row').attr('id'),
studentSelection: jQuery('.row')
});
但是,當我編寫如下代碼時,我可以觸發click事件:
jQuery('.row').click, function(){
console.log('in click event');
});
我不了解發生了什么,因此,如果有人可以闡明它或向正確的方向指點我,我將非常感激。
您的this
情況是完全錯誤的。 this.config.studentSelection
是undefined
以及this.config.fetchStudentDetails
。 this
是指bindEvents
不是init
。 我建議您在這里使用其他模式。 像這樣:
var Student = function (config) {
config = config || {};
var that = this, // In case you need to use the original `this`
isDisplayed = false;
var init = function () {
console.log('in init');
bindEvents();
};
var bindEvents = function () {
console.log('in bind');
config.studentSelection.on('click', '.row', fetchStudentDetails);
console.log('after');
};
var fetchStudentDetails = function () {
// var self = Student; <-- Use `that`
alert('in event');
};
return {
init: init,
bindEvents: bindEvents,
fetchStudentDetails: fetchStudentDetails
}
};
// Create a new student
var student = new Student({ ... });
student.init();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.