2

我正在尝试使用 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) {}
});
4

1 回答 1

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; 行,这个问题不再是一个问题。

于 2013-05-23T13:41:53.383 回答