marionettejs / backbone.marionette

The Backbone Framework
https://marionettejs.com
Other
7.07k stars 1.26k forks source link

this inside ItemView is html object #1595

Closed jSanchoDev closed 10 years ago

jSanchoDev commented 10 years ago

Inside an ItemView, when binding events via events object, this references the HTML object.:

    app.FieldItemView = Backbone.Marionette.ItemView.extend({

        tagName: "li",
        className: "list-group-item field-item",
        template: "#field-item-template",

        events: {
            "click .field-remove": "fieldRemoveClick"
        },

        fieldRemoveClick: function(){
            console.log(this); // I get html button 
        }
    });

    app.ConfigFieldCollectionView = Backbone.Marionette.CollectionView.extend({
        childView: app.FieldItemView,
        tagName: "ul"
    });

The workaraound I use is, in onShow function:

    var that = this;
    this.$(".field-remove").off("click");
    this.$(".field-remove").on("click", function(){
                that.fieldRemoveClick.apply(that);
            });

But it all seems strange. CollectionView is inside LayoutView, which is inside another LayoutView.

EDIT: To make things worse (or better)): after editing all events to the above workaround, I've tried to switch to events: {} -way again. And now it works! This is the second time I'm having this circle of things, I already had such an issue with another view. Maybe this has something to do with Mozilla Firefox caching/JS engine/whatever, rather than Marionette. Now, with the same code I've posted here, callbacks give me the View object as this.

rhubarbselleven commented 10 years ago

Is this with or without models in the collection?

jSanchoDev commented 10 years ago

With models.

samccone commented 10 years ago

hi @SanchoPoncho

I have written a fiddle to try and reproduce.. However everything seems correct. http://jsfiddle.net/F59qp/11/

Click one of the headlines and look at the console.

jSanchoDev commented 10 years ago

hi @samccone !

Somehow I've managed to break your fiddle too) here: http://jsfiddle.net/F59qp/21/ I've edited it to be more like mine, and now it failed me in initialize ((

BTW, thanks a lot for creating a fiddle!

samccone commented 10 years ago

You are overriding render! that is the root of your problem. IF you stop overriding render everything will work just fine :)

jSanchoDev commented 10 years ago

Thanks, now I've got it. Hmm, then is it possible to render the view from template inside script tag?

samccone commented 10 years ago

yep getTemplate: function(){...return template here....}

samccone commented 10 years ago

PS there are plenty of people here if you have questions https://gitter.im/marionettejs/backbone.marionette

jSanchoDev commented 10 years ago

Thanks a lot, once again!)