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

标签 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); 的内容。

我如何拦截该函数并将其放入我的小逻辑中?

最佳答案

您可以提供您自己的 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/

相关文章:

javascript - 从 Bootstrap 模式获取下拉文本

javascript - 正则表达式 - javascript

javascript - 如何检查 DiscordJS V13 中是否有人在语音 channel 中?

javascript - 在另一个模板的元素上引发单击事件

backbone.js - Backbone Marionette 模块作为类似于 Twitter Flight 的小部件

javascript - 当推送到数组时,Typescript undefined 不是一个对象

javascript - 如何使用JSON.parse reviver参数解析日期字符串

javascript - 没有定义 url 的主干验证方法

javascript - 主干架构和 View 管理

backbone.js - 如何向所有 Backbone 模型添加默认错误处理程序?