简体   繁体   English

jQuery / JavaScript在OOP中添加事件触发器

[英]jQuery/JavaScript adding event triggers in OOP

I use the following structure to set out my objects/classes in JavaScript: 我使用以下结构来设置JavaScript中的对象/类:

SelectUser = function(instanceID) {
    this._instanceID = instanceID;

    // Initialize
    this.initialize();
}

SelectUser.prototype = {
    initialize: function () {
        ...
    },

    update(userID) {
        $('#hidden-field-' + this._instanceID).val(userID);
    }
}

This allows me to say: 这让我说:

$selectUser = new SelectUser(1);

Outside of the SelectUser object I need to execute some different code (per instance of SelectUser ) each time the value of the hidden field is changed. 每次更改隐藏字段的值时,我都需要在SelectUser对象之外执行一些不同的代码(每个SelectUser实例)。 My first idea was to try: 我的第一个想法是尝试:

<script type="text/javascript">
    $(document).ready(function () {
        $selectUser = new SelectUser(1);
        $selectUser2 = new SelectUser(2);

        $('#hidden-field-1').change(function () {
            alert('Something');
        });

        $('#hidden-field-2').change(function () {
            alert('Something else');
        });
    });
</script>

However the alert is not triggered. 但是,不会触发警报。 My next thought was to add an event trigger on my update function/method within the SelectUser object/class. 我的下一个想法是在SelectUser对象/类的更新函数/方法上添加事件触发器。 Then I can subscribe to this event per each instance and execute some different code. 然后,我可以为每个实例订阅此事件并执行一些不同的代码。

How do I do this? 我该怎么做呢? I've been using JavaScript for years but I'm fairly new to jQuery and OOP in JavaScript. 我已经使用JavaScript多年了,但是我对JavaScript中的jQuery和OOP还是比较陌生。

.val() doesn't fire the change event since you're changing it programmatically, you can however trigger the event yourself so all the handlers bound for it run. .val()不会触发change事件,因为您以编程方式对其进行了更改,但是您可以自己触发该事件,以便所有绑定到该事件的处理程序运行。 To do that, use .change() , like this: 为此,请使用.change() ,如下所示:

$('#hidden-field-' + this._instanceID).val(userID).change();

To trigger events you have a few options, .trigger('change') triggers it and bubbles up ( .change() without any arguments is just a shortcut for this). 要触发事件,您有几种选择, .trigger('change')会触发它使其冒泡( .change()不带任何参数只是此操作的快捷方式)。 Then there's also .triggerHandler('change') if you just want to trigger event handlers directly on the element but not have it bubble or do the native action....but 99% of the time you're after .trigger('change') or the .change() shortcut. 如果您只是想直接在元素上触发事件处理程序,但又不想使其冒泡或执行本机操作,那么还有.triggerHandler('change')但是您有99%的时间在.trigger('change').change()快捷方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM