Backbone将类添加到集合视图中的最后一个元素?

时间:2014-10-20 14:27:51

标签: javascript jquery backbone.js marionette

在消息视图中,我试图定位集合中的最后一个元素,我只能定位模型而不是el。

下面我让控制台返回el,但由于某些原因它在DOM中不存在,当我尝试向$(this.$el)添加一个类时没有任何反应。所以我很难过。

var Marionette = require('backbone.marionette');

var MessageView = Marionette.ItemView.extend({

    className: 'message',
    template: require('../../templates/message.hbs'),
    initialize: function() {
        this.model.on('change', this.test, this);
    },
    test: function() {
        console.log($(this.$el));

        // Would like to target that last element
        // so I can use somethng like bounce.js to
        // add an animation to the newly added message
    }


});  

module.exports = CollectionView = Marionette.CollectionView.extend({

    className: 'collection',
    initialize: function() {
        // this is triggered in a parent view with the .create method
        this.listenTo(this.collection, 'change', this.render);
    },
    itemView: MessageView

});

我正在尝试为新添加的项添加动画,但我无法定位该视图中的最后一个元素。关于我做错了什么想法?

1 个答案:

答案 0 :(得分:0)

所以我就是这样做的。工作良好。在我的create方法中,我将仅定位集合中的:last项,它将呈现它出现的整个集合,因此每次创建消息时都会创建一个新列表,从而使新创建的消息成为最后一个消息。

// send the message to the DB (client submit triggers this)
if($message.val() != '') {

    $message.val('');

    /* POST the message to the DB and add the message on the client side */
    window.App.data.messages.create(Message, {
        success: function(model) {
            self.scrollChat();
            self.reScroll();
            socket.emit('messageFromClient', Message);
            window.App.core.vent.trigger('app:log', 'Chat View: (POST) new message created!');
            var bounce = new Bounce();
                bounce
                  .translate({
                    from: { x: -300, y: 0 },
                    to: { x: 0, y: 0 },
                    duration: 600,
                    stiffness: 4
                  })
                  .scale({
                    from: { x: 1, y: 1 },
                    to: { x: 0.1, y: 2.3 },
                    easing: "sway",
                    duration: 800,
                    delay: 65,
                    stiffness: 2
                  })
                  .scale({
                    from: { x: 1, y: 1},
                    to: { x: 5, y: 1 },
                    easing: "sway",
                    duration: 300,
                    delay: 30,
                  })
                  .applyTo($('.collection .message:last'));
        }
    });   

}