开发者

jQuery/JavaScript adding event triggers in OOP

I use the following structure to set out my objects/classes in 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. My first idea was to try:

<script type="text/javascript">
    $(document).ready(function () {
        $selectUser = new SelectUser(1);开发者_Go百科
        $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. 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.


.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. To do that, use .change(), like this:

$('#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). 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜