PizzaTheHut
PizzaTheHut

Reputation: 637

Backbone: Wait for multiple updates

I am writing a simple application in Backbone.js and have come across a frustrating situation where my functions bound to the change events are being fired before each model attribute is changed.

In summary, my component is bound to a datepicker, and takes in a start date and end date. I want to wait until both the start date and end date are set, but using the change event fires before both have been set.

Here is some pseudo-code:

define(["jquery", "underscore"], function () {
var model = Backbone.Model.extend({
    initialize: function (options) {
        this._super();

        //Make the items null
        this.set("startDate", null);
        this.set("endDate", null);

        //Listen for changes to data
        this.on("change:startDate change:endDate", this.prepareData, this);
    },
    prepareData: function() {
        var startDate= this.get("startDate");
        if (!startDate)
            return;

        var endDate= this.get("endDate");
        if (!endDate)
            return;

        //DO MY STUFF
    }
});

The result of this is that the first time the 'prepareData' function is fired, I have the new start date and the old end date.

Any clues?

EDIT:

The added complication is that sometimes only date date will be changed, for instance where the user selects a range that lands on the same end date as previously. Seems like I need to wait for a period to check for changed before triggering the function.

Upvotes: 0

Views: 69

Answers (2)

ismaels
ismaels

Reputation: 1

The fact you are registering "change:startDate change:endDate" doesn't mean that the event would be fired only if both of them have changed. They're separeted events, so when the "change:startDate" occur your prepareData function is called and also when the "change:endDate" occur. This is why the first time the prepareData function is called the endData has the old value.

Upvotes: 0

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

You can store the old dates in your model (this._startDate & this._endDate) to check if they have changed :

prepareData: function() {
    var count = 0;
    var startDate= this.get("startDate");
    if (startDate == this._startDate)
        count++;

    var endDate= this.get("endDate");
    if (endDate == this._endDate)
        count++;

    if (count == 0) {
        return;
    } else if (count == 1) {
        // here set your timeout
    }

    this._startDate = startDate;
    this._endDate = endDate;

    //DO MY STUFF
}

Upvotes: 1

Related Questions