如何拦截Model中的'set'函数

时间:2013-09-19 04:25:33

标签: javascript backbone.js

使用常规的getter / setter,你可以做这样的事情

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

使用Backbone虽然你打电话给movie.set('rating', 20);

我怎么能拦截那个放在我的小逻辑中的功能?

1 个答案:

答案 0 :(得分:1)

您可以提供自己的set实现,在将其传递给标准set之前清除传入的值。这样的事情可以解决问题:

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;
}

演示:http://jsfiddle.net/ambiguous/Gm3xD/2/