gpt4 book ai didi

javascript - 主干 ListenTo 不触发

转载 作者:行者123 更新时间:2023-11-28 19:41:49 27 4
gpt4 key购买 nike

我是 Backbone 新手,正在尝试运行以下代码。但我不明白。它无法正常工作。更清楚的是,当我创建集合时,listenTo 不会捕获创建事件。

这是我的代码

var levelIndex=0;
var app = {};
$(function(){
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
startDate: '-3d'
});

//model
app.Level = Backbone.Model.extend({
defaults: {
levelIndex:-1
}
});

//collection
app.Levels= Backbone.Collection.extend({
model: app.Level,
url:'#'
});

//views
app.LevelView = Backbone.View.extend({
events: {
'click .addItems': 'addItems',
'click .clearItems': 'clearItems',
'click .removeLevel':'removeLevel'
},
addItems: function () {
// add items
},
clearItems:function(){
//
},
removeLevel:function(){
//
},
tagName: 'div',
className: 'level active',
template: _.template($('#levelTemplate').html()),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});

//levels view
app.LevelsView = Backbone.View.extend({
events: {
'click .add': 'addLevel'
},

addLevel: function( e ) {
e.preventDefault();
console.log('inside add level function');
var formData = {};
formData['levelIndex']=levelIndex++;
this.collection.create( formData );
console.log('after creating collection');
},

el: '#levels',

initialize: function() {

this.collection=new app.Levels(new app.Level());
//following line of code doesnt work properly
this.listenTo( this.collection, 'create', this.renderLevel );
},

// render levels view by rendering each level in its collection
render: function () {
this.collection.each(function (item) {
this.renderLevel(item);
}, this);
},
// render a level by creating a LevelView and appending the
// element it renders to the levels' element
renderLevel: function (item) {
var levelView = new app.LevelView({
model: item
});
this.$el.append(levelView.render().el);
}
});
new app.LevelsView();
});

最佳答案

集合或模型上没有事件create。在您的情况下,您希望使用将模型添加到集合时触发的事件 add 。但是您会错过一个模型添加,因为您在开始监听之前添加了第一个模型。

http://backbonejs.org/#Events-catalog

关于Collection.create():

Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

关于javascript - 主干 ListenTo 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24903062/

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