2

我有以下模型:

    var User = Backbone.Model.extend({
            defaults: {
                status:     this.constructor.status.OFFLINE,
            },
        },
        {
            status:   {
                OFFLINE: 0,
                ONLINE:  1,
                BUSY:    2,
                AWAY:    3,
            },
        }
    );

我也试过:

status:     User.status.OFFLINE

但我不断收到此错误:

TypeError: 'undefined' is not an object (evaluating 'this.constructor.status.OFFLINE')

或这个:

TypeError: 'undefined' is not an object (evaluating 'User.status')

有什么帮助吗?谢谢

4

1 回答 1

3

您正在尝试引用在创建用户模型时未定义的静态属性。

将您的默认值定义为函数

var User = Backbone.Model.extend({
    defaults: function() {
        return {status: User.status.OFFLINE}
    }
}, {
    status:   {
        OFFLINE: 0,
        ONLINE:  1,
        BUSY:    2,
        AWAY:    3
    }
});

http://jsfiddle.net/nikoshr/6XuC8/

或首先定义您的静态属性,然后扩展 User.prototype 以添加您的默认值:

var User = Backbone.Model.extend({}, {
    status:   {
        OFFLINE: 0,
        ONLINE:  1,
        BUSY:    2,
        AWAY:    3
    }
});

_.extend(User.prototype, {
    defaults: {
        status: User.status.OFFLINE
    }
});

var u = new User();
console.log(u.get('status'));

http://jsfiddle.net/nikoshr/6XuC8/2/

于 2012-10-22T14:26:58.327 回答