thr*_*eez 1 backbone.js backbone-events
我有一个Backbone集合,当我添加一个新模型时,"添加"事件似乎并没有像我期望的那样工作.我绑定了2个视图来监听集合上的添加事件,但只有一个似乎得到了事件的通知,当发生这种情况时,没有PUT请求被发送到我的服务器.当我删除第二个绑定时,另一个工作,并发送PUT请求.这是代码片段:
var FlagList = Backbone.Collection.extend({
model: Flag // model not shown here... let me know if it would help to see
});
var FlagCollectionView = Backbone.View.extend({
el: $('ul.#flags'),
initialize: function() {
flags.bind('add', this.addFlag, this); // this one doesn't fire!!
},
addFlag: function(flag) {
alert("got it 1"); // I never see this popup
}
});
var AddFlagView = Backbone.View.extend({
el: $("#addFlagPopup"),
events: {
"click #addFlag": "addFlag"
},
initialize: function() {
flags.bind('add', this.closePopup, this); // this one fires!!
}
addFlag: function() {
flags.create(new Flag);
},
closePopup: function() {
alert("got it 2"); // I see this popup
}
});
var flags = new FlagList;
var addFlagView = new AddFlagView;
var flagCollectionView = new FlagCollectionView;
Run Code Online (Sandbox Code Playgroud)
一些建议:
ID与类
通过组合一个类和一个id,你已经完全限定了你的选择器.jQuery允许这样,但ID选择器在页面上应该是唯一的,所以el: $('ul.#flags')改为el: $('ul#flags').
利用骨干网
我喜欢将我的集合和/或模型明确地传递给我的视图,collection并model在视图中使用魔术和属性.
var flags = new FlagList;
var addFlagView = new AddFlagView({collection: flags});
var flagCollectionView = new FlagCollectionView({collection: flags});
Run Code Online (Sandbox Code Playgroud)
现在意味着在您的视图中,您将自动访问this.collection
解除绑定事件以避免鬼视图
var FlagCollectionView = Backbone.View.extend(
{
initialize: function (options)
{
this.collection.bind('add', this.addFlag, this);
},
addFlag: function (flag)
{
alert("got it 1");
},
destroyMethod: function()
{
// you need some logic to call this function, this is not a default Backbone implementation
this.collection.unbind('add', this.addFlag);
}
});
var AddFlagView = Backbone.View.extend(
{
initialize: function ()
{
this.collection.bind('add', this.closePopup, this);
},
closePopup: function ()
{
alert("got it 2");
},
destroyMethod: function()
{
// you need some logic to call this function, this is not a default Backbone implementation
this.collection.unbind('add', this.closePopup);
}
});
Run Code Online (Sandbox Code Playgroud)
看起来我必须同意@fguillen,你的问题必须在初始化视图的某个地方,就像在我的评论中我提到它很可能与时间有关,即:在'add之后将你的事件绑定到集合'事件已经解雇了.
| 归档时间: |
|
| 查看次数: |
5047 次 |
| 最近记录: |