gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:57:39 24 4
gpt4 key购买 nike

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

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

关于javascript - 如何拦截Model中的 'set'函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com