Skip to content

remove function does not trigger event when removing last element in array #19

@Kmandr

Description

@Kmandr

When the remove function is used to remove the last element in an array, the remove event is not triggered.
Example code:

$(function() {
    MyModel = Backbone.NestedModel.extend({
        defaults : function() {
            return {
                myArray:["first"]
            };
        }
    });


    MyView = Backbone.View.extend({
        initialize: function() {
            this.model.on("remove:myArray", this.onRemove, this);

            this.model.remove("myArray[0]");

            // the element is removed, but onRemove function is not called
            alert("myArray value is now: " + this.model.get("myArray"));

        },

        onRemove: function() {
            alert("myArray element removed, array is now: " + this.model.get("myArray"));
        }
    });

    new MyView({model:new MyModel()});

});

I've traced this bug to the function remove: function(attrStr, opts). In this function an evaluation is performed to see if an element is actually removed:

(from version 1.1.2, line 88)

// only trigger if an element is actually being removed
      var trigger = !opts.silent && (val.length > i + 1),
        oldEl = val[i];

The variable 'trigger' will be false when the array (in this case, the variable 'val') only has one element and that one element is to be removed. When changing the evaluation to accomodate for array lengths of 1, this issue is fixed.

// only trigger if an element is actually being removed
      var trigger = !opts.silent && (val.length >= i + 1),
        oldEl = val[i];

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions