使用常规的 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); 的内容。
。
我如何拦截该函数并将其放入我的小逻辑中?
最佳答案
您可以提供您自己的 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;
}
关于javascript - 如何拦截Model中的 'set'函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886178/