1

使用常规的 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);.

我如何拦截该功能以放入我的小逻辑中?

4

1 回答 1

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/

于 2013-09-19T04:48:06.643 回答