我尝试将视图动态设置为当有人触摸该项目时,但使用'<%= myClassName%>'在视图内部不起作用。我不能在HTML文件中使用这种技术,因为它会绘制另一个元素,而这不是主意。我也设置了一个模板,但它没有任何内容。我这样做是为了将jQuery Mobile与data-role="content"
联系起来并在内容中呈现视图。有什么想法吗?
这就是我所拥有的:
app.js
var TodoItem = Backbone.Model.extend({
toggleStatus: function(){
if(this.get('status') === 'incomplete'){
this.set({'status': 'complete'});
} else {
this.set({'status': 'incomplete'});
}
this.save();
// PUT /TODOS/1
}
});
var TodoItems = Backbone.Collection.extend({
model: TodoItem,
localStorage: new Backbone.LocalStorage("button"),
initialize: function () {
this.on('remove', this.hideModel, this);
},
hideModel: function (model) {
model.trigger('hide');
}
});
var TodosView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.addOne, this);
},
addOne: function (todoItem) {
var todoView = new TodoView({ model: todoItem });
this.$el.append(todoView.render().el);
},
addAll: function () {
this.collection.forEach(this.addOne, this);
},
render: function() {
this.collection.forEach(this.addOne, this);
this.addAll;
return this;
}
});
var TodoView = Backbone.View.extend({
tagName: 'span',
// THIS IS THE MAIN PROBLEM
className: '<%= status %>',
// END COMMENT
template: _.template( $('#personTemplate').html() ),
events: {
"touchstart": "toggleStatus",
"touchend": "toggleStatus"
},
toggleStatus: function () {
this.model.toggleStatus();
},
remove: function(){
this.$el.remove();
},
initialize: function(){
this.render();
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
this.model.on('hide', this.remove, this);
},
render: function () {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
return this;
}
});
var todoItems = new TodoItems([
{
description: 'Jeffrey Way',
status: "incomplete",
id: 1
},
{
description: 'John Doe',
status: "incomplete",
id: 2
},
{
description: 'Sally Doe',
status: "incomplete",
id: 3
}
]);
var todosView = new TodosView({
el: $('#elem'),
collection: todoItems
});
todosView.render().el
答案 0 :(得分:0)
你可以做到
this.$el.addClass(this.model.get('status'))
在视图的render
方法中。
尝试在视图代码中使用模板值并没有任何意义;在解析对象时设置这些属性,那么它如何知道从哪个对象获取status
?
答案 1 :(得分:0)
解决方案1
var TodoView = Backbone.View.extend({
tagName: 'span',
...})
var x=new TodoView ({className:'sample'});
解决方案2
使用模板!
var TodoView = Backbone.View.extend({
template="<span class=<%-className%>>Some Stuff Goes Here</span>",
...
render:function(){
var $ele=$(_.template(this.template,{className:'sample'}));
this.$el.replaceWith($ele);
this.$el=$ele;
this.delegateEvents(); //inbuilt-method, to re-bind all event handlers
});
答案 2 :(得分:0)
如果我理解正确的话,最好的事情就是听取更改:视图中的状态,以及根据状态值在视图中添加/删除类。
在你的TodoView初始化中:
this.listenTo(this.model, 'change:status', this.changeStatus);
在您的TodoView声明中:
changeStatus : function(model, value, options)
{
// add a class or toggle it or change something in the view..
}