Events between Marionette.CompositeView and Marion

2019-08-18 06:04发布

问题:

I have two modules itemView.js and ListView.js.
Everything works when I fetch the data.

The problem is about the item view (1) when I change the corresponding model.

a) the ListView.js (2) displays all the object which models have closed value equal to false (3)

b) the action closeTask in (1) changes the value of the model
from closed: false to closed: true

c) when b) occurs nothing change,
but if I reload the page I get the right results (the model having the closed value equal to true is not displayed).

How should I fix this issue?


(1)

// itemView.js
var itemView = Marionette.ItemView.extend({

    initialize: function () {
        this.model.on('change', this.render, this);
    },

    events: {
        'click #close': 'closeTask'
    },

    template: itemTemplate,

    tagName: 'li',

    closeTask: function () {
        if (!this.model.get('closed')) {
            this.model.save({
                closed: true
            });
        }
    }

});

(2)

// ListView.js
var ListView = Marionette.CompositeView.extend({

    template: listTemplate,

    itemView: itemView

});

(3)

// Collection
myCollection.attributes = [
    {
        id: 1,
        name: 'bar'
        closed: false
    },
    {
        id: 2,
        name: 'bar2'
        closed: false
    },
    ….
];

P.S.:

When I fetch the collection, the server give me just the models which have the closed attribute equal to false.

app.addInitializer(function () {
    myCollection = new MyCollection();
    myCollection.fetch();
});

回答1:

I did not work with Marionette but I have been working with Backbone, my thought is that Marionette is not refreshing the template or something like it.

What happens if you try this?

// itemView.js
var itemView = Marionette.ItemView.extend({

    initialize: function () {
        this.model.on('change', this.render, this);
    },

    onRender : function(){
       //verify your model:
       console.log( this.model.toJSON() );
       if (this.model.get('closed')) {
          this.$el.fadeOut();//bye bye item
       }
    },

    events: {
        'click #close': 'closeTask'
    },

    template: itemTemplate,

    tagName: 'li',

    closeTask: function () {
        if (!this.model.get('closed')) {
            this.model.save({
                closed: true
            });
        }
    }

});