我是javascript和Backbone.js的新手。我想在初始化时将自定义侦听器绑定到Backbone视图。例如,我想实现这样的目标:
var CampaignListView = Backbone.View.extend({
initialize: function(){
this.on("customFunc")
},
customFunc: function() {
if (this.$el.scrollTop() == 500 ) {
console.log("this has occurred, time to do stuff")
}
}
)}
每当用户滚动到指定位置时,我都可以执行一些代码。
感谢。
答案 0 :(得分:0)
您可以在Backbone Views中使用delegateEvents。例如,您可以附加到视图的滚动事件,但当然每次滚动都会触发。我根据你的例子组建了一个快速而简单的jsfiddle here。下面是一些JavaScript。请注意在代码中使用事件{}。
var CampainListView = Backbone.View.extend({
el: '#list',
events: {
'scroll': 'customFunc'
},
initialize: function() { },
render: function() {
this.$el.html(sampleHtml);
return this;
},
customFunc: function() {
// console.log('scrolling... top is ' + this.$el.scrollTop());
if (this.$el.scrollTop() >= 100 ) {
console.log("this has occurred, time to do stuff")
}
}
});
var view = new CampainListView();
view.render();
答案 1 :(得分:0)
我假设这是你想要在窗口滚动时发生的事情,不是吗?在这种情况下,您有几个选择:
首先是使用remove
方法来清除绑定,更熟悉,更接近你所拥有的东西:
var CampaignListView = Backbone.View.extend({
initialize: function(){
// You probably want to add an identifier to the event name, like 'scroll.campainlist' or something
$(window).on('scroll', _.bind(this.customFunc, this));
},
customFunc: function() {
if (this.$el.scrollTop() == 500 ) {
console.log("this has occurred, time to do stuff")
}
},
remove: function() {
$(window).off('scroll');
Backbone.View.prototype.remove.call(this);
}
)}
另一种选择是使用Event Aggregator,如下所示:
var vent = _.extend({}, Backbone.Events);
$(window).on('scroll', function(ev) {
vent.trigger('window:scroll', ev);
});
var CampaignListView = Backbone.View.extend({
initialize: function(){
this.listenTo(vent, 'window:scroll', this.customFunc);
},
customFunc: function() {
if (this.$el.scrollTop() == 500 ) {
console.log("this has occurred, time to do stuff")
}
}
)}