我正在尝试用Knockback.js设置一些新东西,而现在我遇到了淘汰/敲击整合的问题。问题是,我已成功编写了一个事件处理程序,它将一个新模型添加到Objectives集合中,但UI只注册并添加了第一个这样的添加。它确实成功地将新目标添加到列表中,但只是第一个 - 在此之后,当集合成功地将新模型添加到列表中时,它不会出现在UI中。
<a class="btn" id="click">Click me!</a>
<div id="objectives" data-bind="foreach: objectives">
<h3 data-bind="text: name"></h3>
</div>
这个脚本:
// Knockback script MUST be located at bottom of the page
$(document).ready(new function() {
// instantiate the router and start listening for URL changes
var page_router = new PageRouter();
Backbone.history.start();
// Get JSON value
var objectives;
$.getJSON('json.php', {table: 'objectives'}).done(function(data) {
objectives = new ObjectiveCollection(data);
var view_model = {
objectives: kb.collectionObservable(objectives, {view_model: kb.ViewModel})
};
ko.applyBindings(view_model, $('#objectives').get(0));
});
$('#click').click(function() {
var objective_model = new Objective({category: 3, name: Math.random(), descriptor: 'What up'});
objectives.add(objective_model);
console.log(objectives);
});
});
这里只显示了自定义模型:
/**
* Objectives model
*/
var Objective = Backbone.Model.extend({
// Defaults
defaults: {
id: null,
category: null,
weight: null,
name: null,
descriptor: null
},
// Url to pass to
url : function() {
// Important! It's got to know where to send its REST calls.
// In this case, POST to '/donuts' and PUT to '/donuts/:id'
return this.id ? '/objectives/' + this.id : '/objectives';
}
});
/**
* Basic objectives collection
*/
var ObjectiveCollection = Backbone.Collection.extend({
model: Objective,
initialize: function(models,options) {}
});
答案 0 :(得分:2)
原来,问题出在这里:
var Objective = Backbone.Model.extend({
// Defaults
defaults: {
id: null,
category: null,
weight: null,
name: null,
descriptor: null
}
它一直生成ID为null的模型,程序只显示具有唯一ID的对象。由于ID默认为null,因此它会将没有定义ID的两个对象视为相同。通过擦除id:null;一句话,这个问题就不再是一个问题了。