javascript Backbone.js 视图的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7808938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:23:49  来源:igfitidea点击:

Default values of Backbone.js view?

javascriptbackbone.js

提问by Phillip Whisenhunt

I'm working in Backbone.jsand I was wondering if you can set default values much the same way that you can set the default values of a model?

我正在工作,Backbone.js我想知道您是否可以像设置模型的默认值一样设置默认值?

回答by dira

What you can do is to set your defaults in the initializefunction.

您可以做的是在initialize函数中设置默认值。

defaults: {
  display: 'list'
},

initialize: function() {
  this.options = _.extend({}, this.defaults, this.options);
}

This will work for normal options, but would not override any special options (the ones that Backbone stores on the view object as well - ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'])

这适用于普通选项,但不会覆盖任何特殊选项(Backbone 也存储在视图对象上的选项 - ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName']

See a working demo: http://jsfiddle.net/dira/7MmQE/1/

查看工作演示:http: //jsfiddle.net/dira/7MmQE/1/

回答by Peter Lyons

For Backbone 1.1 or newer

对于 Backbone 1.1 或更新版本

Approach A: OptionsInLiteral with _.defaults in initialize

方法 A:OptionsInLiteral with _.defaults in initialize

var MyView = Backbone.View.extend({
  options: {
    enabled: true,
    align:   "left"
  },
  initialize: function (options) {
    #be sure to do the '|| {}' here so 'new MyView()' works
    this.options = _.defaults(options || {}, this.options);
  }
});

Approach B: Use the viewOptions plugin (or similar)

方法 B:使用 viewOptions 插件(或类似的)

https://github.com/rotundasoftware/backbone.viewOptions

https://github.com/rotundasoftware/backbone.viewOptions

Thanks to @BraveDave for pointing this out in a comment.

感谢@BraveDave 在评论中指出这一点。

For Backbone prior to version 1.1 (historical reference, FYI)

对于 1.1 版之前的 Backbone(历史参考,仅供参考)

Here is the backbone issuewhere it seems like the core team is most likely to get rid of this.optionsand the logic in _configurealtogether.

这是核心团队最有可能摆脱的骨干问题this.options而逻辑则_configure完全相同。

Use an options property and always use this.options

使用选项属性并始终使用 this.options

There is much confusion on this question and even a highly upvoted and accepted incorrect answer. Hopefully this answer demonstrates a truly correct solution as well as pointing out the bugs in all the other candidate answers.

这个问题有很多混乱,甚至是一个高度赞成和接受的错误答案。希望这个答案展示了一个真正正确的解决方案,并指出了所有其他候选答案中的错误。

To work in harmony with the Backbone.Viewparent class, you are supposed to include an optionsproperty of the object literal you pass to Backbone.View.extend.

为了与Backbone.View父类协调工作,您应该包含options传递给 的对象文字的属性Backbone.View.extend

var OptionsInLiteral = Backbone.View.extend({
  options: {flavor: "vanilla"},
  initialize: function (options) {
    console.log("OptionsInLiteral.initialize first argument", options);
    console.log("OptionsInLiteral.initialize this.options", this.options);
  }
});

Here are some examples and what they log to the console.

以下是一些示例以及它们记录到控制台的内容。

new OptionsInLiteral();
    //OptionsInLiteral.initialize first argument undefined
    //OptionsInLiteral.initialize this.options Object {flavor: "vanilla"}
new OptionsInLiteral({flavor: "chocolate"});
    //OptionsInLiteral.initialize first argument Object {flavor: "chocolate"}
    //OptionsInLiteral.initialize this.options Object {flavor: "chocolate"}
new OptionsInLiteral({flavor: "strawberry", sprinkles: true});
    //OptionsInLiteral.initialize first argument Object {flavor: "strawberry", sprinkles: true}
    //OptionsInLiteral.initialize this.options Object {flavor: "strawberry", sprinkles: true}

This will correctly take advantage of Backbone.View._configure, which as of Backbone 1.0.0 looks like this:

这将正确利用Backbone.View._configure,从 Backbone 1.0.0 开始,它看起来像这样:

_configure: function(options) {
  if (this.options) options = _.extend({}, _.result(this, 'options'), options);
  _.extend(this, _.pick(options, viewOptions));
  this.options = options;
},

What this means is:

这意味着:

  • If your view object literal contains options, _configurewill properly treat those as default values, override them with properties passed into the constructor, and set the final resulting object as this.options. Hurray. That's what we want.
  • This will work even if the view constructor is invoked without arguments. Hurray. Also what we want.
  • Because _.resultis used here, the optionsproperty may be either an Objector a function, and if it's a function, it will be called and the return value will be used.
  • 如果您的视图对象文字包含options_configure将正确地将它们视为默认值,使用传递给构造函数的属性覆盖它们,并将最终结果对象设置为this.options. 欢呼。这就是我们想要的。
  • 即使在没有参数的情况下调用视图构造函数,这也将起作用。欢呼。也是我们想要的。
  • 因为_.result这里使用的是 ,options属性可能是 anObject或 a function,如果是函数,就会被调用,并使用返回值。

This is also acceptable and allows the defaults to be unique per instance.

这也是可以接受的,并允许每个实例的默认值是唯一的。

var OptionsFunctionInLiteral = Backbone.View.extend({
  options: function () {
    return {
      flavor: "vanilla",
      created: Date(),
      collection: new Backbone.Collection()
    };
  },
  initialize: function (options) {
    console.log("OptionsFunctionInLiteral.initialize first argument", options);
    console.log("OptionsFunctionInLiteral.initialize this.options", this.options);
  }
});

Here are some examples and what they log to the console.

以下是一些示例以及它们记录到控制台的内容。

new OptionsFunctionInLiteral();
    //OptionsFunctionInLiteral.initialize first argument undefined
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "vanilla", created: "Wed Jun 19 2013 16:20:16 GMT-0600 (MDT)", collection: Backbone.Collection}
new OptionsFunctionInLiteral({flavor: "chocolate"});
    //OptionsFunctionInLiteral.initialize first argument Object {flavor: "chocolate"}
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "chocolate", created: "Wed Jun 19 2013 16:21:17 GMT-0600 (MDT)", collection: Backbone.Collection}
new OptionsFunctionInLiteral({flavor: "strawberry", sprinkles: true});
    //OptionsFunctionInLiteral.initialize first argument Object {flavor: "strawberry", sprinkles: true}
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "strawberry", created: "Wed Jun 19 2013 16:22:26 GMT-0600 (MDT)", collection: Backbone.Collection, sprinkles: true}

Why you should always use this.options

为什么你应该总是使用 this.options

So the above is great with the caveat that if your view's constructor is called with no arguments, inside your initializefunction this.optionswill exist and be correct but the plain optionsargument to the initializefunction will be undefined.

因此,上述需要提醒的是伟大的,如果你的视图的构造函数被调用不带任何参数,你内部的initialize功能this.options会存在,是正确的,但平淡options参数的initialize功能会undefined

initialize: function (options) {
  console.log(options.flavor); //BUG! options is undefined. Uncaught exeption. :-(
  console.log(this.options); //correct
}

Thus when I define my initialize, I don't even specify the optionsargument to the function as a reminder not to use it. In general you want to ignore the optionsargument to initializebecause it doesn't contain the default values anyway.

因此,当我定义我的初始化时,我什至没有指定options函数的参数来提醒不要使用它。通常,您希望忽略options参数 toinitialize因为它无论如何都不包含默认值。

Buggy answer: _.extend(this.defaults, this.options)

错误答案:_.extend(this.defaults, this.options)

This answer has a bug in that it unintentionally modifies the defaults for all future instances every time an instance is instatiated.

此答案有一个错误,即每次实例化时它都会无意中修改所有未来实例的默认值。

var DefaultsExtendView = Backbone.View.extend({
  defaults: {flavor: "vanilla"},
  initialize: function (options) {
    console.log("initialize 1st argument", options);
    this.options = _.extend(this.defaults, this.options);
    console.log("initialize this.options", this.options);
  }
});

new DefaultsExtendView(); //OK
new DefaultsExtendView({flavor: "chocolate"}); //OK
new DefaultsExtendView(); //BUG! You get chocolate instead of vanilla

Buggy answer: if (options.foo)

错误答案:如果(options.foo)

var myView = Backbone.View.extend({
    foo: "default_value",

    initialize: function(options) {
        if(options.foo) {
            foo = options.foo;
        }
    }
});

new myView(); //BUG! options is undefined, uncaught exception
//TypeError: Cannot read property 'foo' of undefined

Beware of options object and instance-specific defaults

注意选项对象和特定于实例的默认值

One of the answers to this question suggests this:

这个问题的答案之一表明:

var DefaultsView = Backbone.View.extend({
  defaults: {
    collection: new Backbone.Collection()
  },
  initialize: function () {
    _.defaults(this.options, this.defaults);

Which is almost certainly not what you want and a bug. If you make 10 views, they will all be sharing the same instance of Backbone.Collectionas there will just be 1 instance created when the view subclass is defined. This is sure to confuse you when you add a model to view9's collection and it shows up in all of the views. What you more likely want is a different new collection instance for each view instance, and to get that you need to make optionsbe a function as in my example above.

这几乎肯定不是您想要的并且是错误。如果您创建 10 个视图,它们将共享相同的实例,Backbone.Collection因为在定义视图子类时只会创建 1 个实例。当您将模型添加到 view9 的集合并且它显示在所有视图中时,这肯定会让您感到困惑。您更可能想要的是为每个视图实例创建一个不同的新集合实例,并且要获得它,您需要将options其设为一个函数,如我上面的示例所示。

Summary of the proper way to do this

执行此操作的正确方法的摘要

  1. use options: {...}or options: function () {...}
  2. Declare your initializewithout any arguments
  3. Access your properly-defaulted options as this.options
  1. 使用options: {...}options: function () {...}
  2. 声明你initialize没有任何参数
  3. 访问您正确默认的选项 this.options

Example Boilerplate

示例样板

var MyView = Backbone.View.extend({
  options: {flavor: "vanilla"},
  initialize: function () { //note no declared arguments
      //use this.options here as needed and all is well
  }
});

Working jsfiddle

工作 jsfiddle

http://jsfiddle.net/DUc25/

http://jsfiddle.net/DUc25/

回答by Brian Genisio

For Backbone 1.1 or newer

对于 Backbone 1.1 或更新版本

Approach A: OptionsInLiteral with _.defaults in initialize

方法 A:OptionsInLiteral with _.defaults in initialize

var MyView = Backbone.View.extend({
  options: {
    enabled: true,
    align:   "left"
  },
  initialize: function (options) {
    #be sure to do the '|| {}' here so 'new MyView()' works
    this.options = _.defaults(options || {}, this.options);
  }
});

Approach B: Use the viewOptions plugin (or similar)

方法 B:使用 viewOptions 插件(或类似的)

backbone.viewOptions

主干.viewOptions

Thanks to @BraveDave for pointing this out in a comment.

感谢@BraveDave 在评论中指出这一点。

For Backbone prior to version 1.1 (historical reference, FYI)

对于 1.1 版之前的 Backbone(历史参考,仅供参考)

Here is the backbone issuewhere it seems like the core team is most likely to get rid of this.optionsand the logic in _configurealtogether.

这是核心团队最有可能摆脱的骨干问题this.options而逻辑则_configure完全相同。

Use an options property and always use this.options

使用选项属性并始终使用 this.options

There is much confusion on this question and even a highly upvoted and accepted incorrect answer. Hopefully this answer demonstrates a truly correct solution as well as pointing out the bugs in all the other candidate answers.

这个问题有很多混乱,甚至是一个高度赞成和接受的错误答案。希望这个答案展示了一个真正正确的解决方案,并指出了所有其他候选答案中的错误。

To work in harmony with the Backbone.Viewparent class, you are supposed to include an optionsproperty of the object literal you pass to Backbone.View.extend.

为了与Backbone.View父类协调工作,您应该包含options传递给 的对象文字的属性Backbone.View.extend

var OptionsInLiteral = Backbone.View.extend({
  options: {flavor: "vanilla"},
  initialize: function (options) {
    console.log("OptionsInLiteral.initialize first argument", options);
    console.log("OptionsInLiteral.initialize this.options", this.options);
  }
});

Here are some examples and what they log to the console.

以下是一些示例以及它们记录到控制台的内容。

new OptionsInLiteral();
    //OptionsInLiteral.initialize first argument undefined
    //OptionsInLiteral.initialize this.options Object {flavor: "vanilla"}
new OptionsInLiteral({flavor: "chocolate"});
    //OptionsInLiteral.initialize first argument Object {flavor: "chocolate"}
    //OptionsInLiteral.initialize this.options Object {flavor: "chocolate"}
new OptionsInLiteral({flavor: "strawberry", sprinkles: true});
    //OptionsInLiteral.initialize first argument Object {flavor: "strawberry", sprinkles: true}
    //OptionsInLiteral.initialize this.options Object {flavor: "strawberry", sprinkles: true}

This will correctly take advantage of Backbone.View._configure, which as of Backbone 1.0.0 looks like this:

这将正确利用Backbone.View._configure,从 Backbone 1.0.0 开始,它看起来像这样:

_configure: function(options) {
  if (this.options) options = _.extend({}, _.result(this, 'options'), options);
  _.extend(this, _.pick(options, viewOptions));
  this.options = options;
},

What this means is:

这意味着:

  • If your view object literal contains options, _configurewill properly treat those as default values, override them with properties passed into the constructor, and set the final resulting object as this.options. Hurray. That's what we want.
  • This will work even if the view constructor is invoked without arguments. Hurray. Also what we want.
  • Because _.resultis used here, the optionsproperty may be either an Objector a function, and if it's a function, it will be called and the return value will be used.
  • 如果您的视图对象文字包含options_configure将正确地将它们视为默认值,使用传递给构造函数的属性覆盖它们,并将最终结果对象设置为this.options. 欢呼。这就是我们想要的。
  • 即使在没有参数的情况下调用视图构造函数,这也将起作用。欢呼。也是我们想要的。
  • 因为_.result这里使用的是 ,options属性可能是 anObject或 a function,如果是函数,就会被调用,并使用返回值。

This is also acceptable and allows the defaults to be unique per instance.

这也是可以接受的,并允许每个实例的默认值是唯一的。

var OptionsFunctionInLiteral = Backbone.View.extend({
  options: function () {
    return {
      flavor: "vanilla",
      created: Date(),
      collection: new Backbone.Collection()
    };
  },
  initialize: function (options) {
    console.log("OptionsFunctionInLiteral.initialize first argument", options);
    console.log("OptionsFunctionInLiteral.initialize this.options", this.options);
  }
});

Here are some examples and what they log to the console.

以下是一些示例以及它们记录到控制台的内容。

new OptionsFunctionInLiteral();
    //OptionsFunctionInLiteral.initialize first argument undefined
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "vanilla", created: "Wed Jun 19 2013 16:20:16 GMT-0600 (MDT)", collection: Backbone.Collection}
new OptionsFunctionInLiteral({flavor: "chocolate"});
    //OptionsFunctionInLiteral.initialize first argument Object {flavor: "chocolate"}
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "chocolate", created: "Wed Jun 19 2013 16:21:17 GMT-0600 (MDT)", collection: Backbone.Collection}
new OptionsFunctionInLiteral({flavor: "strawberry", sprinkles: true});
    //OptionsFunctionInLiteral.initialize first argument Object {flavor: "strawberry", sprinkles: true}
    //OptionsFunctionInLiteral.initialize this.options Object {flavor: "strawberry", created: "Wed Jun 19 2013 16:22:26 GMT-0600 (MDT)", collection: Backbone.Collection, sprinkles: true}

Why you should always use this.options

为什么你应该总是使用 this.options

So the above is great with the caveat that if your view's constructor is called with no arguments, inside your initializefunction this.optionswill exist and be correct but the plain optionsargument to the initializefunction will be undefined.

因此,上述需要提醒的是伟大的,如果你的视图的构造函数被调用不带任何参数,你内部的initialize功能this.options会存在,是正确的,但平淡options参数的initialize功能会undefined

initialize: function (options) {
  console.log(options.flavor); //BUG! options is undefined. Uncaught exeption. :-(
  console.log(this.options); //correct
}

Thus when I define my initialize, I don't even specify the optionsargument to the function as a reminder not to use it. In general you want to ignore the optionsargument to initializebecause it doesn't contain the default values anyway.

因此,当我定义我的初始化时,我什至没有指定options函数的参数来提醒不要使用它。通常,您希望忽略options参数 toinitialize因为它无论如何都不包含默认值。

Buggy answer: _.extend(this.defaults, this.options)

错误答案:_.extend(this.defaults, this.options)

This answer has a bug in that it unintentionally modifies the defaults for all future instances every time an instance is instatiated.

此答案有一个错误,即每次实例化时它都会无意中修改所有未来实例的默认值。

var DefaultsExtendView = Backbone.View.extend({
  defaults: {flavor: "vanilla"},
  initialize: function (options) {
    console.log("initialize 1st argument", options);
    this.options = _.extend(this.defaults, this.options);
    console.log("initialize this.options", this.options);
  }
});

new DefaultsExtendView(); //OK
new DefaultsExtendView({flavor: "chocolate"}); //OK
new DefaultsExtendView(); //BUG! You get chocolate instead of vanilla

Buggy answer: if (options.foo)

错误答案:如果(options.foo)

var myView = Backbone.View.extend({
    foo: "default_value",

    initialize: function(options) {
        if(options.foo) {
            foo = options.foo;
        }
    }
});

new myView(); //BUG! options is undefined, uncaught exception
//TypeError: Cannot read property 'foo' of undefined

Beware of options object and instance-specific defaults

注意选项对象和特定于实例的默认值

One of the answers to this question suggests this:

这个问题的答案之一表明:

var DefaultsView = Backbone.View.extend({
  defaults: {
    collection: new Backbone.Collection()
  },
  initialize: function () {
    _.defaults(this.options, this.defaults);

Which is almost certainly not what you want and a bug. If you make 10 views, they will all be sharing the same instance of Backbone.Collectionas there will just be 1 instance created when the view subclass is defined. This is sure to confuse you when you add a model to view9's collection and it shows up in all of the views. What you more likely want is a different new collection instance for each view instance, and to get that you need to make optionsbe a function as in my example above.

这几乎肯定不是您想要的并且是错误。如果您创建 10 个视图,它们将共享相同的实例,Backbone.Collection因为在定义视图子类时只会创建 1 个实例。当您将模型添加到 view9 的集合并且它显示在所有视图中时,这肯定会让您感到困惑。您更可能想要的是为每个视图实例创建一个不同的新集合实例,并且要获得它,您需要将options其设为一个函数,如我上面的示例所示。

Summary of the proper way to do this

执行此操作的正确方法的摘要

  1. use options: {...}or options: function () {...}
  2. Declare your initializewithout any arguments
  3. Access your properly-defaulted options as this.options
  1. 使用options: {...}options: function () {...}
  2. 声明你initialize没有任何参数
  3. 访问您正确默认的选项 this.options

Example Boilerplate

示例样板

var MyView = Backbone.View.extend({
  options: {flavor: "vanilla"},
  initialize: function () { //note no declared arguments
      //use this.options here as needed and all is well
  }
});

Working jsfiddle

工作 jsfiddle

http://jsfiddle.net/DUc25/

http://jsfiddle.net/DUc25/

回答by Andrew

var DefaultsView = Backbone.View.extend({
  defaults: {
    collection: new Backbone.Collection()
  },
  initialize: function () {
    _.defaults(this.options, this.defaults);
    // Ensures keys with special meaning (model, collection, id, className, etc.), are attached directly to the view
    Backbone.View.prototype._configure.apply(this, arguments);
  },
  render: function () {
    console.log(this.collection);
  }
});

var view = new DefaultsView();

view.render();

回答by ddan

An attempt at duck punching. From Backbone's source code:

鸭拳的尝试。来自 Backbone 的源代码:

var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this._configure(options || {});
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
};

We'll override _configure:

我们将覆盖_configure

// Save _configure method
var _oldConfigure = Backbone.View.prototype._configure;

Backbone.View.prototype._configure = function(options){
    _.defaults(options, this.defaults); 
    _oldConfigure.call(this, options);
};

Now Backbone.View behaves the same as Backbone.model with regards to defaults, and you don't even need to do anything in the constructor/initialize method.

现在 Backbone.View 在默认值方面的行为与 Backbone.model 相同,您甚至不需要在构造函数/初始化方法中执行任何操作。

回答by yun_cn

By Backbone.View's explanation, it says

根据 Backbone.View 的解释,它说

constructor / initializenew View([options])

When creating a new View, the options you pass are attached to the view as this.options, for future reference. There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagNameand attributes. If the view defines an initialize function, it will be called when the view is first created. If you'd like to create a view that references an element already in the DOM, pass in the element as an option: new View({el: existingElement}).

构造函数/初始化新视图([选项])

创建新视图时,您传递的选项作为this.options附加到视图,以供将来参考。有几个特殊选项,如果通过,将直接附加到视图:modelcollectionelidclassNametagNameattributes。如果视图定义了初始化函数,它将在第一次创建视图时调用。如果您想创建一个引用 DOM 中已有元素的视图,请将该元素作为选项传入:new View({el: existingElement})。

I wounder why the defaults is not used in the view in the same way that are used in the Model and Collection.

我想知道为什么默认值没有以在模型和集合中使用的相同方式在视图中使用。

回答by Blueshirts

This stack is a little misleading to me. Peter Lyons answer seems like the current correct one though does not have the most votes.

这个堆栈对我来说有点误导。Peter Lyons 的答案似乎是当前正确的答案,尽管没有最多的选票。

From the Backbone docs...

从骨干文档...

When creating a new View, the options you pass — after being merged into any default options already present on the view — are attached to the view as this.options for future reference.

创建新视图时,您传递的选项 - 在合并到视图中已经存在的任何默认选项之后 - 作为 this.options 附加到视图以供将来参考。

http://backbonejs.org/#View-constructor

http://backbonejs.org/#View-constructor

I was able to make it work by implementing an options in the class definition.

我能够通过在类定义中实现一个选项来使其工作。

MyScope.MyView = Backbone.View.extend({
    options: {
        default_prop: 'value1',
        another_default: 'value2'
    }
}

回答by jseto

If I understand the question correctly, you can set defaults in this way:

如果我正确理解了问题,您可以通过这种方式设置默认值:

scope.MyView = Backbone.View.extend({
    x: 'x',
})

var obj = new scope.MyView({
    y: 'y',
});

console.log( this.options );
// output: { x: 'x', y:'y' }

The problem, and the behavior does not fully reflect what is stated in the View constructor documentation, is that compound objects are not fully copied. This is because _configureuses underscore.js _.extendand it is not recursive.

问题和行为并未完全反映 View 构造函数文档中所述的内容,即复合对象未完全复制。这是因为_configure使用 underscore.js_.extend并且它不是递归的。

That means that if you do something like this:

这意味着如果你做这样的事情:

scope.MyView = Backbone.View.extend({
    x: {
        a: 'a',
    }
})

var obj = new scope.MyView({
    x: {
        b: 'b',
    }
});

console.log( this.options );
// output: { x: { b:'b' } }

does not work as expected. This is likely to happen if you pass attributes to the view an have default attributes. The attributes you pass will be overwritten.

没有按预期工作。如果您将属性传递给具有默认属性的视图,则可能会发生这种情况。您传递的属性将被覆盖。

回答by Brave Dave

Use the backbone.viewOptions plugin, which does exactly what you are looking for:

使用backbone.viewOptions 插件,它完全符合您的要求:

// Add the view options plugin functionality to all our views.
Backbone.ViewOptions.add( Backbone.View.prototype );

MyView = Backbone.View.extend( {
    options : [
        "type", // normal options are declared like so
        { "label" : "OK" } // options with defaults are declared like so
     ],

    initialize : function( options ) {
        this.setOptions( options ); // attaches declared options to the view

        console.log( this.label ); // outputs "OK"
        console.log( this.type ); // outputs "button"
    }
} );

new MyView( { type : "button" } );

回答by Ronni Egeriis Persson

The correct solution is similar to dira's. Simply specifying an options object in the view spec will contain default values for the options object: http://jsfiddle.net/h3cAU/1/

正确的解决方案类似于 dira 的解决方案。简单地在视图规范中指定一个选项对象将包含选项对象的默认值:http: //jsfiddle.net/h3cAU/1/

var ViewDefaultsDemo = Backbone.View.extend({
  options: {
     display: 'list'
  },

  render: function() {
    console.log(this.options.display)
  }
});

See the source for View._configure for additional info: https://github.com/documentcloud/backbone/blob/0.9.10/backbone.js#L1332-L1334

有关更多信息,请参阅 View._configure 的来源:https: //github.com/documentcloud/backbone/blob/0.9.10/backbone.js#L1332-L1334