我正在尝试用Knockback.js设置一些新的东西,现在我遇到了一个关于knockout/knockback集成的问题。问题是,我已经成功地编写了一个事件处理程序,它向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) {}
});发布于 2013-05-23 21:41:53
事实证明,问题位于以下位置:
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;行,这个问题就不再是问题了。
https://stackoverflow.com/questions/16715528
复制相似问题