观点表现得很尴尬

时间:2014-01-01 09:42:05

标签: javascript backbone.js view

考虑Backbone.js源代码的一部分:

// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

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

我想知道为什么只将'model','collection','el','id','attributes','className','tagName','events'分配给View实例。我发现这很烦人。我通常需要发送一些额外的参数。是否可以替换_.extend(this, _.pick(options, viewOptions)); _.extend(this, options));

1 个答案:

答案 0 :(得分:0)

为什么不将您的额外数据存储在属性哈希中?

如果你真的想直接在视图上设置其他属性,你也可以将它作为属性选项传入,然后在initialize方法中的view对象上设置它:

var MyView = Backbone.View.extend({
    initialize: function() {
        var self = this;

        if (this.attributes) {
            _.each(this.attributes, function(val, key) {
                self[key] = val;
            });
        }
    }
});

var view = new MyView({ attributes: { foo: 'bar' } });