gpt4 book ai didi

Backbone view.render() 中的 jQuery 不规则性

转载 作者:行者123 更新时间:2023-12-01 04:04:36 33 4
gpt4 key购买 nike

什么情况下会发生这种情况:

 this.$el.append(ret);  //doesn't work

$(this.el).append(ret); //works

我像这样实例化 View :

new allViews.UserProfile({el: '#main-content-id',collection: collections.users}),

所以也许我应该使用 $el 而不是 el 来实例化 View 。为什么 Backbone 会做出这样的区分,这太疯狂了。

我之前就应该提到这一点,但这是我正在做的一件非标准的事情。让我恼火的一件事是 Backbone 不允许 View 中使用“默认值”。这是错误的 - 例如 - 您可能需要 View 的默认集合,但如果您在构造函数中传递集合,那么它将覆盖默认值。相当合理。所以基本上我尝试手动将 Backbone.Model 中的内容复制为 Backbone.View。

所以这是 View 的全部内容,供您欣赏:

    var UserProfileView = Backbone.View.extend({

defaults: function () {
return {
model: null,
collection: collections.users,
childViews: {}
}
},
events: {

},

constructor: function () {
this.givenName = '@UserProfileView';
Backbone.View.apply(this, arguments);
},

initialize: function (opts) {

Backbone.setViewProps(this, opts); //has side effects

},
render: function () {

var data = this.collection.models;

renderThis.bind(this)(UserProfileView.template);


function renderThis($template) {
var ret = EJS.render($template, {
users: data
});

//this.$el.append(ret);

$(this.el).append(ret);

}
return this;
}
},
{ //class properties
template: template
}
);

这是每个 View 都会运行的非标准函数,该函数在 view.initialize() 函数中调用:

  Backbone.setViewProps = function(view,options){

var opts = options || {};

var temp = _.defaults({}, opts, _.result(view, 'defaults'));

for(var prop in temp){
if(temp.hasOwnProperty(prop) && prop !== undefined){
if(temp[prop]!==undefined){
view[prop] = temp[prop];
}
}
}
};

所以我认为正在发生的事情是,当我将 el 作为选项传递时,它会过早地附加到 View 上,然后 Backbone 过早地调用

 this.setElement(_.result(this, 'el'));

来自 Backbone 源代码的内部

 _ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
this.setElement(this._createElement(_.result(this, 'tagName')));
this._setAttributes(attrs);
} else {
this.setElement(_.result(this, 'el'));
}
},

依次调用

 _setElement: function(el) {
this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
this.el = this.$el[0];
},

最佳答案

我完全不确定你想做什么,但我只会在评论中回答你的问题:

I think the best way someone could help me is to help create a better way to have default attributes for a View

One thing that irritates me is that Backbone doesn't allow for 'defaults' in views.

我不明白是什么阻止您在主干 View 上定义默认值并允许使用可以传入的选项参数进行覆盖:

var View = Backbone.View.extend({
initialize: function(options){
this.defaults = {
name: "default",
color: "blue"
};

this.attributes= $.extend({}, this.defaults, options);
}
})

您可以通过在实例化 View 时传入这些属性来覆盖它们:

var view = new View({name: "Alex", color: "red"}); 

http://jsfiddle.net/C9wew/7299/

关于Backbone view.render() 中的 jQuery 不规则性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31467844/

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