vvMINOvv
vvMINOvv

Reputation: 1850

How to intercept the 'set' function in Model

With regular getter/setters you can do something like this

function setRating (num) {
    var min = 0;
    var max = 10;

    var result = num;

    if      (num < min)   result = min;
    else if (num > max)   result = max;

    this.rating = result;
}

setRating(20);  //rating == 10

With Backbone though you'd call something like movie.set('rating', 20);.

How could I intercept that function to place in my little logic?

Upvotes: 1

Views: 273

Answers (1)

mu is too short
mu is too short

Reputation: 434665

You could provide your own implementation of set that cleans up incoming values before handing them off to the standard set. Something like this should do the trick:

set: function(key, val, options) {
    // This first bit is what `set` does internally to deal with
    // the two possible argument formats.
    var attrs;
    if(typeof key === 'object') {
        attrs = key;
        options = val;
    }
    else {
        (attrs = {})[key] = val;
    }

    // Clean up the incoming key/value pairs.
    this._clean_up(attrs);

    // And then punt to the standard Model#set
    return Backbone.Model.prototype.set.call(this, attrs, options);
},
_clean_up: function(attributes) {
    if('rating' in attributes) {
        // Force the rating into the desired range...
    }
    return attributes;
}

Demo: http://jsfiddle.net/ambiguous/Gm3xD/2/

Upvotes: 1

Related Questions