简体   繁体   中英

Backbone view change event not firing when input manipulated by code

In my Backbone model's View I have:

events: {
    'change textarea' : 'changeContentTextarea',
    ...

When user enters a text manually into the textarea, it triggers and do this:

    this.model.set('content', this.$el.find('textarea').val());

But it doesn't fire when the content is changed in program (using jQuery):

    txtarea.val(finalText);

and so the model's attribute does not update and only the text in the textarea changes.

Is there any event that I can bind to address this problem? Or how can I fire the event after I change the content using jQuery?

From https://api.jquery.com/change/

Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.

So you have to trigger the change event yourself

$("textarea").val(finalText).trigger("change");

The answer below is right and only if you need to know if the event is triggered by user or by JS, you can do this:

$("textarea").val(finalText).trigger("customChange");

and define the listen event like that:

events: {
     'customChange textarea' : 'doSomethingWithJSEvent',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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