如何知道我点击的项目Id?我的代码如下:
$(function() {
ipl.mvc.view.openings_view = ipl.mvc.view.view_base.extend({
template: '/assets/t/plmt/companies.tmpl.html',
ID: '#tmpl_openings',
events: {
"click #edit": "editpost"
},
initialize: function() {
var _this = this;
_.bindAll(this, 'addOne', 'addAll', 'render', 'editpost');
_this.loadTemplate(_this.template, function() {
_this.model = new ipl.mvc.model.companies_model([]);
_this.model.view = _this;
_this.model.bind('change', _this.render, _this);
});
}
,
render: function() {
var _this = this
jsonData = _this.model.toJSON();
_.each(jsonData, function(model) {
$(_this.ID).tmpl(model).appendTo(_this.el);
return _this;
});
}
,
editpost: function(e) {
console.log("EDIT CLICKED");
e.preventDefault();
var ele = $(e.target);
console.log(ele);
_this.model = new ipl.mvc.collection.companies_collection([]);
var id = _this.model.get("id");
alert(id);
}
});
});
和模板
<a href="!/editpost/${id}" data-id="${id}"><button id="edit" ><img src="/assets/img/pencil.png" /></button></a>
我需要在编辑函数中使用id,而不是从模板中获取${id}
,并且我遵循这些步骤,但我没有得到它?如何从模板中获取点击项的${id}
?
发布于 2012-03-05 17:32:51
实际上你需要的是:
editPost:函数(E){ e.preventDefault();var id = $(e.currentTarget).data("id");var item = this.collection.get(id);}
remark我注意到你的代码有太多的结束标记,所以它不能在这里运行,我还注意到在你的editPost中,你尝试了_this,但你从来没有声明过_this。您应该在该方法中使用var _this = this;
。
remark 2我不明白为什么你甚至需要一个数据id在这个例子中,有两种呈现视图的方法,要么是视图绑定了一个集合,要么是它有一个模型。将集合绑定到视图时,可能需要从单击的元素中获取正确的id,以便在集合中找到正确的模型
但是在您的示例中,视图有一个绑定到它的模型,所以您只有1个ID,您可以通过调用this.model.get('id');
获得它。我相信上面的整个代码示例都是从使用视图中集合的另一个示例中复制过来的,因为您的呈现和data-id属性的使用都表明了这一点。
发布于 2014-07-01 15:40:57
这是另一个(backbone的更新版本?)实现方法:(我看到@Sander在他的评论中显示了model.get
方法)
var AppointmentView = Backbone.View.extend({
events: {
'click' : 'alertTitle'
},
alertTitle : function(e) {
// this.model.get('id') is what you're looking for
alert( this.model.get('title') );
}
});
https://stackoverflow.com/questions/9563663
复制相似问题