gpt4 book ai didi

javascript - 如何使用 Backbone View 在下划线模板中渲染模型属性

转载 作者:行者123 更新时间:2023-12-03 08:44:04 24 4
gpt4 key购买 nike

我在这个问题上花了 2 天,似乎找不到名称值没有传递到下划线模板的原因。

我正在从 URL 获取用户,该 URL 返回一个值 { "name": "UserName"} (以及更多),我可以在控制台中看到该值。然后我获取模型,并使用成功回调将其传递给 View 。模板已呈现,但没有值。

在 View 中,我可以记录属性,但它们不会在下划线模板中呈现。

为什么该名称没有在模板中呈现?没有错误,并且在 View 中我可以记录模型中的属性。

我使用 requirejs、backbone 和 underscore(以及 jekyll 来创建 html),并且我有以下代码:

主要

require([ 'app' ], function(App){
App.initialize();
});

应用程序

define(['jquery','underscore','backbone','users/model','users/view'
], function($, _, Backbone, User, ProfileLinkView){
var initialize = function(){
console.log("Working")
user = new User();
user.fetch({
success : function(){
console.log(user)
var profileLink = new ProfileLinkView({ model : user });
console.log("pL:", profileLink.el);
}
});
}
return {
initialize: initialize
};
});

查看

define(['backbone','users/model'], function( Backbone, User ) {

var ProfileLinkView = Backbone.View.extend({
el: '#profilelink',
//template: _.template( "<a href='#'>Len</a>"),
initialize : function(){
this.render();

this.listenTo(this.model, 'change', this.test);
},
test : function(){
alert( "change" );
},
render: function() {
console.log("v", this.model.attributes );
data = this.model.attributes;
this.template = _.template( "<a href='#'><%= name %></a>", this.model.toJSON() );
this.$el.html( this.template( this.template() ) );
return this;
},
})

return ProfileLinkView
});

型号

define(['underscore','backbone',], function(_, Backbone, User){
var User = Backbone.Model.extend({
url: 'http://localhost:3000/users/0',
})
return User;
});

结果不正确

<li class="dropdown" id="profilelink"><a href="#"></a></li>

应该是:

<li class="dropdown" id="profilelink"><a href="#">UserName</a></li>

最佳答案

我不确定这部分

this.template = _.template( "<a href='#'><%= name %></a>", this.model.toJSON() );
this.$el.html( this.template( this.template() ) );

你能尝试改成这样吗?

this.template = _.template( "<a href='#'><%= name %></a>");
this.$el.html( this.template( this.model.toJSON() ) );

underscore's template的第二个参数是模板设置而不是数据。并且您应该将数据传递到已编译的模板中。

关于javascript - 如何使用 Backbone View 在下划线模板中渲染模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32965066/

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