简体   繁体   中英

How can I select an element from inside a Marionette event handler?

EDIT: Added more code

I'm listening for an event on my model like this: (this is my view)

var view = Marionette.ItemView.extend({

    tagName: 'tr',
    template: viewtemplate,

    modelEvents: {
        "change:highscore": "highchange"
    },

    highchange: function (model) {
        var elem = this.$('.send');
        console.log(elem);
        elem.hide();
        this.render();
    }
});

And my template:

<td class="cusername">{{username}}</td>
<td class="highscore">

<div class="box">
    <button class="send"></button>
        <span>Send</span>
    </button>
</div>

(this is inside my Marionette.ItemView.extend({...}); )
When my model changes the highscore I want the send element to get hidden but when I do the above nothing changes. The console.log(elem) gives me the element as an object[div.send] which is the correct element, however it doesn't get hidden.

Does this have something to do with the lifecycle of marionette? How can I change an element to be hidden as a result of an event on the model?

Do you have more than one element with the 'send' class within this view context? If so, you may just need to disambiguate relative to the target element. If you understand the relationship between the target of the event itself and the element you want to manipulate, you can access it that way:

highchange: function (e) {
    var elem = $(e.target).find('.send'); // if .send is a child element
    var elem = $(e.target).closest('.send'); // if .send is a parent element
}

It happens because you rerender entire view after element hiding. You can hide element after calling render function. Render is very expensive operation, i suggest you refresh view manually:

var View = Marionette.ItemView.extend({

    tagName: 'tr',

    template: viewtemplate,

    ui: {
        $username: '.username',
        $send: '.send'
    },

    modelEvents: {
        'change': 'onChangeModel'
    },

    onChangeModel: function (model) {
        if (model.hasChanged('highscore')) this.ui.$send.hide();

        if (model.hasChanged('username')) this.ui.$username.text(model.get('username'));        
    }
});

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